Working with circular inclusion in a parent / child class relation

Suppose I created a class, say Parent, that has a compound relationship with Child. The parent class contains a list of children.

I want all children to contain a reference to the parent, so each child element contains a pointer Parent.

This will cause a circular inclusion. I refer to Childin parent.h and I refer to Parentin child.h. Therefore, Parentyou will need to include Child, which should include Parent.

What is the best way to get around this?

+3
source share
2 answers

You will need to use a forward declaration:

//parent.h
class Child; //Forward declaration
class Parent
{
    vector<Child*> m_children;
};

//child.h
class Parent; //Forward declaration
class Child
{
    Parent* m_parent;
};
+8

Child Parent, #include "parent.h" child.h. forward class Parent; child.h parent.h . child i.e. child.cpp #include "parent.h" Parent.

+2

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


All Articles