0

For example, I have two classes, Game and Logic. Game has-a unique pointer to an object named m_Logic.

class Game {

public:
    Game(){} 

private:
    std::unique_ptr<Logic> m_Logic;
}`

class Logic {

public:
    Logic()
bool Run(Game &pGame) { 
    pGame.GetObjectPtr().DoStuff() return true; 
}

In the Logic Class I use a method referring to the Game object, so ultimately I can call:

this->m_Logic->Run(*this);

From within the Game Class, and not have to constantly pass in individual object references coming from the Game Object itself, into it's components when I need the component to do its work while knowing about what Game contains.

Since they are both dependent on each-other in this case, what alternatives can be made to keep them as independent as possible, but still know about one another to work with while following good design practice? And my goal is to do this without having to declare references of the same individual objects that the game has and keeping parameters as clean as possible.

Thanks all in advance.

1 Answers1

2

If you don't want to pass in a Game every time, then the easiest way is to just have them point to each other. I'm assuming from your code example that Game owns Logic... so Logic should then have a non-owning pointer to Game:

class Game;

class Logic {
    Game* m_Game; // non-owning
};

class Game {
    std::unique_ptr<Logic> m_Logic;
};

Since the Game already owns m_Logic, it should be pretty straightforward to assign itself to m_Logic. If Game itself constructs the Logic object, then you can even make m_Game a Game& for added clarity.

Barry
  • 286,269
  • 29
  • 621
  • 977