0
votes
  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

2
Can you post some code and the compiler error?hmjd
@hmjd : undefined reference to class_name::aAlexDan
Note: that's the linker giving you the error, not the compiler. It's the same effect as declaring a (free) global variable as extern in a header but not actually defining it in a .cpp file. A global variable must have a consistent memory location known to all compilation units, otherwise they won't see each other's changes to its value. As such, it must have external linkage and be defined exactly once. It is not like a static (compilation unit local) variable.pmdj
@pmjordan : it's not the linker, the error is during the compiling time .AlexDan
undefined reference is normally a linker error. If you're using an IDE, you might not realise that compiling has finished and it's progressed to linking.pmdj

2 Answers

5
votes

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.

0
votes

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?