c++includedependenciesabstract

C++ Cycling includes (Three classes, two virtual)


I don´t know, how to declare some classes in my project, which have include statements that are circular.

(Map -> Object -> Object_Manager -> Map ->...)

I found nothing (useful) for three classes and tried some possibilities (many forms of forward declaration) for two classes - without success...

Here is my design for the classes (reduced form):

Map.h

//some other includes
#include "Object.h"

#ifndef Map_H
#define Map_H

class Map{
   public: 
     Map();
     virtual ~Map();
     void move_object(Object* object, int x, int y); 
     // some other functions and members, that should be usable for and with Objects
}

Object.h

#include "Object_Manager.h"
        
#ifndef Object_H
#define Object_H
        
class Object { 
   public:  
      Object();     
      virtual ~Object();
      void interact_with(Object* object); 
      //some other stuff
        
   protected: 
      Object_Manager* object_manager;  
}

Object_Manager.h

#include "Map.h"

class Object_Manager{
   public: 
      Object_Manager(); 
      ~Object_Manager(); 

      Map* map; 

      //some other stuff
}

Map.h (and its children) is using Objects in the .cpp and Object.h´s children are using Map* map from Object_Manager.h - if this is important.

With this code I get many compiler-ERRORs. The compiler didn´t like my other solutions as well, so how could this work?

Important: what must stay in the .h and what in the .cpp files? And what is eventually needed for the child-classes?

Thanks!


Solution

  • Remove inclusion...

    #include "Object_Manager.h"
    

    From "Object.h" and use forward declaration instead...

    class Object_Manager;
    

    Similarly, remove inclusion...

    #include "Map.h"
    

    from "Object_Manager.h" and use forward declaration instead...

    class Map;