Ricc Ricc - 1 year ago 47
C++ Question

C++: Conceptual circular include problem

I'm making a component based entity system for a game engine.

I have an entity class, which has to include the component base class header in order to define the array of components

private Component* components[ 123 ]

However, in the component base class I have to define a
private Entity* ownerEntity
, beacuse it is crucial that a component knows who it belongs to!

This results in Entity.h needing Component.h and vice-versa -> Circular reference

How can I solve this?

Answer Source

As long as you only need your class to contain pointers or references to the other classes, you can skip the real include file and use an empty forward declaration like class Component;.

You will need the full include in the source file where you dereference the pointers or use the reference to call methods on Component.