Edwin W. Edwin W. - 1 month ago 6
C++ Question

Circular dependencies and better ways to do it?

I really enjoy coding but currently every project I started has ended early due to the circular dependencies really messing with me and my head. I have been having problems, I am trying to make games, however due to my class structure I rely on some circular dependencies which cause problems in the end that almost always grow and go out of my control.
How I usually structure it:


  1. class Game


    1. class GameContext


      1. class Window


        1. class GameContext


      2. class EventManager


        1. class GameContext


      3. class StateManager


        1. class GameContext






I use this since I sometimes need to access for example the Window from the EventManager. In the end I always seem to lose it. Is there a better way for something like this that avoids circular dependencies? And if not how do you really go about thinking when you have to deal with them? I thought I understood them but clearly not.

What I am trying to archive is a centeral storage "Context" class which other classes could access but I do not know how to avoid circular dependencies in such a case.

To really show what I mean you can look at THIS, my latest failed atempt.
The problem I have with this current structure seems to be something to do with a dependency between the EventManager and the GameStateManager since in EventManager I get a error on GameStateID being undefined.

Answer

I managed to figure out my problem and it was more in the way of how I thought about it, I thought I wanted a structure like this:

  1. class Game
    1. class GameContext
      1. class Window
        1. class GameContext
      2. class EventManager
        1. class GameContext

But what I actually wanted was:

  1. class Game
    1. class Window
    2. class EventManager
    3. class GameContext

Where every every class except GameContext contains a pointer to a GameContext. Also one of my problems was my understanding of forward declaration, I did not understand them and mixed and spread them everywhere because I thought it was magic.