Reputation: 61
I have a class that has a static pointer to another class, which is a singleton. The problem that I seem to be getting though is that I cannot set the pointer from within the constructor of said class. Here is my current code:
class B;
class A
{
public:
A();
~A();
};
class B
{
public:
B();
~B();
static A* a;
};
A::A() {
A* B::a = this;
}
Now, the problem that I seem to be getting is that I cannot define B::a in the "current scope". In addition, the "this" pointer can only be used in a "nonstatic member function".
I think the problem has to do with defining the static class variable within another class function, but I am not sure.
Upvotes: 3
Views: 2593
Reputation: 4827
You should define all static members outside the class declaration:
class B;
class A
{
public:
A();
~A();
};
class B
{
public:
B();
~B();
static A* a;
};
A* B::a; // HERE
A::A()
{
B::a = this; // and there was an error here too
}
Don't forget to define the other ctors/dtors.
Upvotes: 0
Reputation:
First of all, static class members have to be defined as well as declared. static A* a;
in the body of class B is merely a declaration, and you need to define a. Note that every class member must have a single definition, that's why we usually define static members in the appropriate .cpp
files for classes. Obviously, this happens outside of the class body. You also cannot define a static member in scope of a function.
So, move the definition of a outside of the constructor's scope, like this:
class B
{
public:
B();
~B();
static A* a;};
A* B::a = 0; // Good idea to set a default value for the pointer
Note, however, that the value of a
will contain a 0 until at least one object of type A is created.
Upvotes: 3