AlexDan
AlexDan

Reputation: 3331

static member variables initialization c++

  1. Why the compiler gives me an error when I don't initialize a value to a static member variable? Shouldn't it be initialized to 0?
  2. Why I have to initialize member variable outside the class? (is this illegal because if you do so, and change the value of this static member variable inside the main function and you create an object of this clas, it will re-assign the static mamber variable to the old value) whereas const static member variable are legal to be initilized inside the class (and this is possible because you can't change the value of this static member variable anyway)?

Error: undefined reference to class_name::a

Upvotes: 0

Views: 1338

Answers (2)

hmjd
hmjd

Reputation: 121961

From the error posted, the linker is stating that the variable has not been defined, not that it has not been explicitly initialised:

class A
{
    // declaration.
    static int x;
};

// definition (in this case without explicit initialisation).
int A::x;

The linker should not emit an error and the compiler should not emit a warning, as long as no attempt is made to use the static variable before it has been assigned an initial value.

Upvotes: 5

Bo Persson
Bo Persson

Reputation: 92211

A static member is not really stored in any of the objects created, because it is shared between all objects of that class.

It should only be created once, even if you create many objects of that class. Or even if you create no objects of the class. Therefore you have to do it separately.

Compilers warn about all kinds of uninitalized variables, not only the static ones. Having a variable without a value is generally not very useful, so these warnings are good. Adding an = 0 is not too hard, is it?

Upvotes: 0

Related Questions