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
2009-08-25 01:26:02
Note that the OP didn't say whether there's a type or an object on the left side of the dot.
sbi
2009-08-25 03:44:58
@sbi, which is why I qualified it in my answer :)
JaredPar
2009-08-25 03:47:24
@JaredPar: Yes, but only in the second-last word. My disagree module had long since kicked in by then. `:)`
sbi
2009-08-25 08:53:00
+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
2009-08-25 01:27:06
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
2009-08-25 03:36:25
`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
2009-08-25 03:48:51
+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
2009-08-25 02:05:13