Forward Declaration and Circular Dependence

I have two classes: Entity and Level. Both must access each other's methods. Therefore, using #include, there is a circular dependency problem. Therefore, to avoid this, I tried to send a level declaration in Entity.h:

class Level { }; 

However, since Entity needs access to methods at the Level, it cannot access these methods because it does not know that they exist. Is there a way to resolve this without re-declaring most of the level in Entity?

+6
source share
2 answers

The correct forward declaration is simple:

 class Level; 

Note the absence of curly braces. This tells the compiler that there is a class called Level , but nothing is reported about its contents. Then you can use pointers ( Level * ) and links ( Level & ) for this class undefined.

Note that you cannot directly create Level instances, since the compiler must know the size of the class to create the variables.

 class Level; class Entity { Level &level; // legal Level level; // illegal }; 

To be able to use Level in Entity methods, you should ideally define Level methods in a separate .cpp file and only declare them in the header. Separating declarations from definitions is C ++ best practice.

 // entity.h class Level; class Entity { void changeLevel(Level &); }; // entity.cpp #include "level.h" #include "entity.h" void Entity::changeLevel(Level &level) { level.loadEntity(*this); } 
+7
source

You have two options:

  • use pointers, in which case your forward ads should be in order.
  • embed the methods of one class, in which case, if you include the .h file, you can use the methods of another.

Personally, I would go on the way No. 1, it became cleaner and provided better access. I use a lot of shared_ptr, so I don't need to worry about deleting ...

 Entity.h: class Level; class Entity { private: Level* m_pLevel; public: bool CheckLevel (); bool WasItThere(); Level.h class Entity; class Level { private: Entity* m_pEntity; public: public bool CheckMyStuff(); public bool CheckItOut() { return m_pEntity->WasItThere();} } Entity.cpp #include "Level.h" bool Entity::CheckLevel () { return true; } bool Entity::CheckLevel() { return m_pLevel->CheckMyStuff(); } bool Entity::WasItThere() { return true; } Level.cpp bool Level::CheckMyStuff() { return true; } bool Level::CheckItOut() { return m_pEntity->WasItThere(); } 
+1
source

Source: https://habr.com/ru/post/946046/


All Articles