Reputation: 2010
class B { /* ... */ };
class A {
public:
A() { obj = NULL; }
private:
static B* obj;
};
However this produces huge mass of linker errors that symbol obj is unresolved.
What's the "correct" way to have such private static class member without these linker errors?
Upvotes: 2
Views: 1107
Reputation: 525
Linking errors are because you also need to declare static variables outside class definition purely for linking purpose and static memory allocation as
B* A::obj;
Upvotes: 1
Reputation: 385154
You declared the static member, but you did not define it.
Further, you set its value whenever any instance of A is constructed, whereas in fact you only want it initialised once.
class B;
class A {
private:
static B* obj;
};
B* A::obj = NULL;
As your class A definition is probably in a header file, you should ensure that the definition of obj (that I added) goes in one (and one only) .cpp file. This is because it must appear only once in your compiled project, but the contents of the header file may be #included
multiple times.
Upvotes: 1
Reputation: 1797
You have to initialize obj in a cpp file:
B* A::obj = NULL;
You are not allowed to initialize it in a constructor, since it is a static variable.
Upvotes: 3
Reputation: 72336
http://www.parashift.com/c++-faq/ctors.html#faq-10.12
(And as @peoro noted, please remember to end every class definition with a ;
).
Upvotes: 3
Reputation: 8744
You need to add
B *A::obj = NULL;
to one of your cpp files. Also note that if you set obj in A's constructor, that means that whenever you create an A object you reset obj again - since it is static, there is only one obj that is shared among all A instances.
Upvotes: 6
Reputation: 64223
You need to define like this :
this is in the header :
class B { ... }
class A {
public:
A() { obj = NULL; }
private:
static B* obj;
}
this is in the source
B* A::obj = NULL;
Upvotes: 6