Reputation: 16029
Can I access static member variables of a class using dot notation or should I stick in access operator which is double colon?
Upvotes: 11
Views: 4288
Reputation: 81
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).
Upvotes: 4
Reputation: 94645
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;
}
Upvotes: 18
Reputation: 754595
You must use the double colon access operator. This is the only valid way of accessing static members from a class name.
Upvotes: 2