Reputation: 1133
Why is this invalid in C++?
class CLS
{
public:
static int X;
};
int _tmain(int argc, _TCHAR* argv[])
{
CLS::X=100;
return 0;
}
Upvotes: 2
Views: 759
Reputation: 7667
It isn't that the static member must be INITIALIZED at global scope, but rather that the static member must have storage allocated for it.
class CLS {
public:
static int X;
};
int CLS::X;
int _tmain(int argc, _TCHAR* argv[])
{
CLS::X=100;
return 0;
}
Upvotes: 5
Reputation: 14870
They can be changed inside of main, like in your example, but you have to explicitely allocate storage for them in global scope, like here:
class CLS
{
public:
static int X;
};
int CLS::X = 100; // alocating storage, usually done in CLS.cpp file.
int main(int argc, char* argv[])
{
CLS::X=100;
return 0;
}
Upvotes: 5
Reputation: 17567
static
members aren't part of class object but they still are part of class scope. they must be initialized independently outside of class same as you would define a member function using the class scope resolution operator.
int CLS::X=100;
Upvotes: 0
Reputation: 4555
Once you define a static data member, it exists even though no objects of the static data member's class exist. In your example, no objects of class X exist even though the static data member CLS::X has been defined.
Upvotes: 0