yoyo
yoyo

Reputation: 1133

Why must the static member be initialized outside main()?

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

Answers (4)

John R. Strohm
John R. Strohm

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

ruslik
ruslik

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

cpx
cpx

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

THE DOCTOR
THE DOCTOR

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

Related Questions