11

Can I access static member variables of a class using dot notation or should I stick in access operator which is double colon?

3 Answers 3

18

If you have an instance variable you may use dot operator to access static members if accessible.

#include <iostream> using namespace std; class Test{ public: static int no; }; int Test::no; int main(){ cout << "\n" << Test::no; Test::no=100; Test a; cout << "\n" << a.no; return 0; } 
Sign up to request clarification or add additional context in comments.

2 Comments

thanks alot. Because I compile my codes using VC express with dot notation that access the static member variable of a class like Test.no but no errors.
Test.no is not a valid way to refer to static members. The left side of the member access operator must be an object. So, Test::no or a.no. Of course, for statics, prefer Test::no.
4

It's not necessarily the "can you" question (because the compiler will often let you off with warnings), but the "should you" question.

Static data members are not part of the object, and therefore should not be treated as such.

Accessing a static data member as a "normal" data member can make the code less readible too, since it may imply different semantics (though this is usually unlikely).

1 Comment

It still can be useful, especially when writing template code. It enables you to call static functions / access static members of the given type while only having a value of that type, not a type name (such as when returned by a template function where the return type cannot be typedef-ed). Probably hard to imagine.
2

You must use the double colon access operator. This is the only valid way of accessing static members from a class name.

3 Comments

Note that the OP didn't say whether there's a type or an object on the left side of the dot.
@sbi, which is why I qualified it in my answer :)
@JaredPar: Yes, but only in the second-last word. My disagree module had long since kicked in by then. :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.