Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cross reference and circular dependency. Header including itself indirectly

placeable.h

#include "selectable.h"

class placeable : selectable
{
..
};

selectable.h

#include "game.h"


class selectable
{
..
};

game.h

#include "placeable.h"

class game
{
...
class placeable* holding;
...
};

Basically placeable.h includes selectable.h which includes game.h which includes placeable.h again.

The only solution i can think of is placing the placeable* in a new header, making it static/global and then include this new header in game.h and selectable.h.

I'm sorry i dint include header guards in the upper code. I assumed it was obvious. Header guards does not help in this case because of the inheritance, same thing goes with forward declaring.

like image 739
user1113563 Avatar asked Jan 18 '23 23:01

user1113563


1 Answers

Only include headers if you MUST

Use forward declaration in preference to including:

You only need to include the header for class X iff:

  • You have a member of the class 'X'
  • You derive from the class 'X'
  • You pass a parameter of class 'X' by value.

Otherwise a forward declaration will suffice.

//  -> Don't do this #include "placeable.h"
class     placeable;  // forward declare
                      // Fine if you are using a pointer.

class game
{
    ...
    class placeable* holding;
    ...
};

PS. Add header guards.

like image 176
Martin York Avatar answered Feb 06 '23 17:02

Martin York