1

My project at the moment is set up something like this

game.cpp

#include "game.h"
#include "enemy.h"

class Game {
    public:
    
    ...
    ...
    std::vector<Enemy> enemies;
    ...
};

enemy.cpp

#include "game.h"

class Enemy {
    public:

    ...
    ...
    void turn(Game* game);
    ...
};

I obviously understand that in this case, this creates a circular dependency. The Game object needs a reference to Enemy to keep a list of enemies and the Enemy has a function for doing its turn that needs a reference to the Game object. I'm not really sure how to break up this circular dependency. I tried to make a header file with forward class declarations but I was getting hit with "invalid use of incomplete type" errors.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Acemcbean
  • 336
  • 1
  • 3
  • 7
  • [https://stackoverflow.com/questions/625799/resolve-build-errors-due-to-circular-dependency-amongst-classes](https://stackoverflow.com/questions/625799/resolve-build-errors-due-to-circular-dependency-amongst-classes) – drescherjm Feb 15 '21 at 22:47

1 Answers1

1

If those are the only dependent functions, you could declare and initialize in the following order:

class Game;

class Enemy {
public:
    void turn(Game* game);
};

class Game {
public:
    std::vector<Enemy> enemies;
};

Live example: https://ideone.com/g6Vmwi

scohe001
  • 15,110
  • 2
  • 31
  • 51