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?
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;
};
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With