In C
has a concept called forward declaration
. I know this concept for functions, where I can declare the existence of the function to, only at a later time, explain how is the implementation.
In C++
, this concept applies to classes as well. That response in the international Stack Overflow deals precisely with your problem (cyclical dependency between classes) using class declaration as forward declaration
. The original answer also provides many interesting details of how the compiler works, I will summarize here how to avoid these problems in a pragmatic way.
In order to be able to reference a class (as a pointer or reference), it must be declared before. For your case of actors in a world, we can put the classes of that 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 the Actor class in the World header (with forward declaration
); as Actor depends on World, also do the forward declaration
world-class.
Actor
andWorld
need to see each other? I’m just seeing dependence onWorld.getActor
– Jefferson Quesado
Yes. There are several roles in Actor that use World class getters and setters
– Felipe Nascimento
adapted my answer
– Jefferson Quesado