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
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; } 2 Comments
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.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
You must use the double colon access operator. This is the only valid way of accessing static members from a class name.