views:

297

answers:

3

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!

+4  A: 

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;
Tom
+8  A: 

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;

    ...
};
Adam Maras
You don't need forward declarations in both headers. You can have one `#include` the other.
Charles Salvia
Yes, but for compilation times, if you can get away with it, it's better to use forward declarations rather than including the whole class file wherever possible.
Eclipse
+2  A: 

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;
  ...
};
...
Edward Brey