4

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.

user1113563
  • 41
  • 1
  • 3

5 Answers5

5

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.

Martin York
  • 257,169
  • 86
  • 333
  • 562
3

This means you have not properly encapsulated the functionality of your design. It should be higher-level includes lower level, not same-level includes same-level. If game is the higher level then selectable should not include game.h.

Steve C
  • 647
  • 3
  • 6
2

This is a solved problem. It's called header guards. Try this inside ALL of your header files:

#ifndef __NAMEOFTHEFILE_H__
#define __NAMEOFTHEFILE_H__
// nothing goes above the ifndef above

// everything in the file goes here

// nothing comes after the endif below
#endif

Also, you can do this (this is known as a forward reference):

// game.h

class placeable;

class game { ...
    placeable* p;
};
jmucchiello
  • 18,754
  • 7
  • 41
  • 61
0

There are two problems:

  1. Circular headers dependency. Solution - #ifndef ...
  2. Allocating space for unknown type. Solution - class placeable;

See more here

Community
  • 1
  • 1
Andrey Burykin
  • 700
  • 11
  • 23
-1

Use header guards in each of your header files to avoid this problem. In general, your header files should like this:

#ifndef PLACEABLE_H
#define PLACEABLE_H

//
// Class definitions and function declarations
//

#endif
shargors
  • 2,147
  • 1
  • 15
  • 21