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

1k views Asked by At

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!

3

There are 3 answers

2
Adam Maras On BEST ANSWER

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;

    ...
};
0
Tom On

Its not because the private constructor.

Its because you have a circular dependency. So when you try to compile class A, you need to compile class B, which needs compiled class A, and so on.

Try a forward declaration.

In the header file where gameState is defined

class actionHandler;
0
Edward Brey On

The problem has nothing to do with the private constructors. In a given translation unit (.cpp file and all included .h files), the C++ compiler doesn't recognize the identifier for a class until the class is declared. This poses a problem when two classes contain members that refer to each other. The solution is called a "forward declaration", which is just the class name, but no body. It may look something like this in your case:

== gameState.h ==

...
// Note no #include for "actionHandler.h" (but there would be in gameState.cpp)

class actionHandler;

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

== actionHandler.h ==

...
#include "gameState.h"

// No forward declaration needed.

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