I always struggle to discover why I'm getting "Undefined reference to static variable" in my code, and I always end up in these questions:
Undefined reference to static variable c++
Undefined reference to static variable
I understand that I need to define my data outside the class declaration.
In the example:
class Helloworld {
public:
static int x;
void foo();
};
int Helloworld::x = 0; // Or whatever is the most appropriate value
// for initializing x. Notice, that the
// initializer is not required: if absent,
// x will be zero-initialized.
I must initiate x to some value. But what about static members that are class instances? Why simply the compiler won't make an instance for me with the default constructor?
If I write
class A {
public:
B b;
}
then I can do
A a;
a.b;
I don't need to define B b
outside the A
class declaration. Why do I need to do it for the static example below?
class A {
public:
static B b;
}
B A::b