Search code examples
c++dependenciessystem-calls

C++ object hierarchy - how to manage circular dependencies?


I want to make two classes: an object and an object_manager, but I'm confused about how they should see/include each other. I've heard that it's forbidden for two headers to include each other and if my code dependencies has circles then it's a bad code design and usually it should be like a hierarchy structure (town->house->furniture and furniture shouldn't know about town existence).

But here I have the object_manager which knows and holds all the objects, and the objects should have an option to create new objects, but then they should call the object_manager which will force them to know about it existence and this will create a circle in the structure, which is bad.

It's like one process wants to create a new process by calling the OS system calls, so the OS and the process knows about each other.

Is there a way I can implement this in the right code design, or should it just be bad sometimes?

I thought maybe the objects should have a special place where they will store all their "system calls", and the object_manager will check it from time to time, but maybe there is a better way.


Solution

  • Use forward declaration:

    class ObjectManager;
    
    class Object
    {
    private:
       ObjectManager* m_objManager;
       ....
    public:
       ....
    };
    

    In .cpp file you can include the ObjectManager.h Also instead of ObjectManager make the interface which will give you more abstraction for implementation IObjectManager.