Jack
Jack

Reputation: 23

Cyclic dependendy between header with typedef

I have such situation

In file GameServer.h:

class ServerGameStruct; //I can't simply include ServerGameStruct.h
                        // because of cyclic dependency
class GameServer {
public:
    class Client { };
private:
    ServerGameStruct gameStructure_;
}

and in file ServerGameStruct.h

#include "GameServer.h"

class ServerGameStruct {
public:
    typedef GameServer::Client Client;
    // some method which use type Client *
    // no class members with type Client 
}

And after compile I get error that GameServer::gameStructure_ use undefined class GameServerStruct.

How resolve that kind of header cyclic dependency?

Upvotes: 2

Views: 92

Answers (4)

justin
justin

Reputation: 104698

Another approach would be to introduce an abstract type, such as AbstractGameClient. This type could provide the interface ServerGameStruct needs, then GameServer::Client would derive from AbstractGameClient. To illustrate:

AbstractGameClient.h

class AbstractGameClient {
protected:
  AbstractGameClient();
  virtual ~AbstractGameClient();
public:
  void somePublicMember() const;
  virtual void somePublicMemberTheSubclassMustSupply() const = 0;
};

GameServer.h

class GameServer {
public:
    class Client : public AbstractGameClient {
      virtual void somePublicMemberTheSubclassMustSupply() const { ... }
      ...
    };
private:
    ServerGameStruct gameStructure_;
};

ServerGameStruct.h

#include "AbstractGameClient.h" // << or just a forward of AbstractGameClient,
                                //    then use AbstractGameClient in the *.cpp

class ServerGameStruct {
public:
  void something(AbstractGameClient& pGameClient) {
    pGameClient.somePublicMember();
    pGameClient.somePublicMemberTheSubclassMustSupply();
  }
};

Upvotes: 0

Some programmer dude
Some programmer dude

Reputation: 409356

The easiest solution is to make gameStructure_ a pointer:

std::unique_ptr<ServerGameStruct> gameStructure_;

The reason being that a pointer to a class doesn't need the complete definition of the class to be declared. While when you declare a direct instance of a class, like in your code, then you need the complete definition of the class.

You can also make it a reference, but then you have to initialize it in the GameServer constructor.

Upvotes: 1

metal
metal

Reputation: 6332

You need to make gameStructure_ a (smart) pointer or reference so its type definition isn't required there. If you use a pointer, you'll need a destructor, even if it's empty, in the cpp file so you (or preferably your smart pointer) can delete the complete type.

Upvotes: 0

spiritwolfform
spiritwolfform

Reputation: 2293

Use a pointer

ServerGameStruct* gameStructure_;

In this case you will need to handle your ServerGameStruct's lifetime manually. Smart pointers can help you do that

Upvotes: 0

Related Questions