user1113563
user1113563

Reputation: 41

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.

Upvotes: 4

Views: 6422

Answers (5)

Andrey Burykin
Andrey Burykin

Reputation: 738

There are two problems:

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

See more here

Upvotes: 0

Loki Astari
Loki Astari

Reputation: 264631

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.

Upvotes: 5

shargors
shargors

Reputation: 2157

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

Upvotes: -1

jmucchiello
jmucchiello

Reputation: 18984

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;
};

Upvotes: 2

Steve C
Steve C

Reputation: 647

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.

Upvotes: 3

Related Questions