Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dealing with circular inclusion in a parent/child class relationship

Assume I've made a class, say Parent, that has a composition relation with Child. The parent class holds a list of children.

I want all children to hold a reference to the parent, so every child holds a Parent pointer.

This will cause circular inclusion. I refer to Child in parent.h and I refer to Parent in child.h. Therefore Parent will need to include Child, which needs to include Parent.

What's the best way to work around this?

like image 896
Pieter Avatar asked Nov 15 '10 12:11

Pieter


2 Answers

You'll have to use 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;
};
like image 72
Andreas Brinck Avatar answered Nov 12 '22 22:11

Andreas Brinck


Since only a pointer of Parent is stored inside the Child class there is no need to do a #include "parent.h" in the child.h file. Use the forward declaration of class Parent; in child.h instead of inclding parent.h in there. In the source file of child i.e. child.cpp you can do #include "parent.h" to use the Parent methods.

like image 30
Naveen Avatar answered Nov 13 '22 00:11

Naveen