tags:

views:

217

answers:

3

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

+2  A: 

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

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

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;
}
adatapost
@litb - I appreciate your help.
adatapost
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.
sasayins
`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`.
Johannes Schaub - litb
+2  A: 

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).

PinkTriangles