Reputation: 39
I've been busting my head for some time now trying to figure out a solution. I want to inherit from a class with a static pointer but I geterror LNK2001: unresolved external symbol "protected: static class cGame * cEvent::mGame" (?mGame@cEvent@@1PAVcGame@@A)
Optimaly I would just initialize my class cEvent once and then dont pass pointers in the inherited classes.
#ifndef EVENT_H
#define EVENT_H
#include "game.h"
class cEvent
{
protected:
static cGame* mGame;
public:
cEvent(){;}
virtual void doEvent(){;}
};
class cEventExitButton: public cEvent
{
private:
public:
cEventExitButton(cGame *g){mGame = g;}
void doEvent(){mGame->getWindow()->close();}
};
#endif
Upvotes: 1
Views: 2906
Reputation: 5310
You have only declared mGame
in the header file:
static cGame* mGame;
This tells the compiler that mGame
exists and what its type is, but doesn't actually create space for mGame
to exist. For this, you need to define it in a cpp file:
cGame* cEvent::mGame = [some intial value];
Now the linker has a location for mGame
and anyone referencing it can point to that location. The linker can't do this with the header since multiple files may include the header. We only want a single location for mGame
though, so it needs to go in a cpp file.
Upvotes: 1
Reputation: 500873
You have to define mGame
in a .cpp
file:
cGame* cEvent::mGame = ...;
(replace the ...
as appropriate.)
Upvotes: 0
Reputation: 361702
You need to define the static
member outside the class:
##include "game.h"
//do this .cpp file
cGame* cEvent::mGame = nullptr;
//or initialize it as : cGame* cEvent::mGame = create object!
Note that the static member in the class is only declaration, that is not definition.
Upvotes: 5