In C
has a concept called forward declaration
. I know this concept for functions, where I can declare the existence of the function to, at a later time, explain how the implementation is.
In C++
, this concept applies to classes as well. This answer in International Stack Overflow deals precisely with your problem (cyclic dependency between classes) using the class declaration as forward declaration
. The original answer also provides many interesting details of how the compiler works, I'll summarize here how to avoid these problems in a pragmatic way.
In order to reference a class (such as pointer or reference), it must be declared first. For your case of actors in a world, we can put the classes of this semantic level in the same header and code files.
To use this way, do so in the header:
#ifndef WORLD_ACTORS_H
#define WORLD_ACTORS_H
class Actor; // apenas a forward declaration, sem implementação
class World; // idem
// real código relativo à classe Actor
class Actor {
...
}
class World {
Actor* getActor(std::string id);
...
}
In the code file, just include the header described above and be happy.
If you want to continue using classes in separate files (which is fair), you need to declare in the World header the Actor class (with forward declaration
); as Actor depends on World, also do forward declaration
of World class.