Chris Chris - 1 year ago 68
C++ Question

Mutual inclusion with singleton

I currently have a problem with mutual inclusion in a project of mine (C++).

Normally, if I had a mutual inclusion problem, I'd easily solve it by either forward declaration or redesigning the classes a bit. But this time, I'm stuck:

I have a class called Game, which creates and launches core game systems, where one of these is called GraphicsSystem.
In the Game constructor, a GraphicsSystem object is dynamically created and stored in a GraphicsSystem* pointer. Looks like this:

Game::Game ()
gfxSys = new GraphicsSystem(80, new Camera());

Now my GraphicsSystem class needs to access a Game class's method at one point to get the player object, which is stored within the Game object. The respective part looks like this (Game is btw a singleton!):

void GraphicsSystem::handleFrame ()
ElementList elements = Game::instance()->getPlayer()->getEnvironment()->getElements();

Now I tried forward declaration in both directions already, but that wouldn't satisfy the compiler. I could of course also just put the player pointer into the graphics system, but I really don't want to do that, since he doesn't belong there.

Is there any way to resolve this without me having to change the design too much? I'm really stumped right now, so I hope you guys can help me.

I'm using Visual Studio 2010 (Visual C++).

Thank you in advance!

Answer Source

Forward declare GraphicsSystem in Game.h. Include Game.h in GraphicsSystem.h if it needs it. Include Game.h and GraphicsSystem.h in Game.cpp. Include Game.h and GraphicsSystem.h in GraphicsSystem.cpp. That should work based off the code you posted.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download