Search code examples
c++static-membersprivate-constructor

c++: Private constructor means no definition of that classes objects inside headers?


Yet another question, go me!... Anyway, I have 2 classes with private constructors and static functions to return an instance of that class. Everything was fine, I have a main.cpp file where I managed to get hold of my gameState object pointer, by doing:

gameState *state = gameState::Instance();

But now I seem to have a problem. For the sake of convenience, I wanted both the gameState instance and a actionHandler instance to retain a copy of the pointer to each other. So I tried to include in each other's header files:

gameState *state;

and

actionHandler *handler;

This however, doesn't seem to work... I get "error C2143: syntax error : missing ';' before '*'" errors on both of those lines... Can you not define variables of a certain classe's in the header if that class has a private constructor? Or is the problem something else? OR maybe it is because the pointer to teh instance is stored as a static member?

EDIT: Thanks guys! It's amazing the amount of c++ knowledge I'm getting these last couple of days.. awsome!


Solution

  • It looks like you need to add a forward declaration of the opposite class to each class's header file. For example:

    class actionHandler;
    
    class gameState
    {
    private:
        actionHandler *handler;
    
        ...
    };
    

    and:

    class gameState;
    
    class actionHandler
    {
    private:
        gameState *state;
    
        ...
    };