Somewhat related to this question https://softwareengineering.stackexchange.com/questions/388977/how-to-reach-the-parent-object.
I have a class that contains a member object of another class, and these classes are always instantiated with a parent-child object relationship. Sometimes the child object needs to access the parent object, and I would prefer to instantiate the child with a pointer or reference to the parent to do so. I need the parent class and child class definitions in separate files.
When attempting to follow the suggestions from the linked question I would need to include each class's header in the other definition, which would cause compiler errors for circular inclusions.
Reference variable:
//file:child.h
#include "parent.h"
class Child
{
private:
Parent &parent;
public:
// constructor
Child(Parent &p) : parent(p) {}
// other members
};
//file:parent.h
#include "child.h"
class Parent
{
private:
Child child;
public:
// Constructor
Parent() : child(*this) {}
// other members
};
Pointer variable:
//file:child.h
#include "parent.h"
class Child
{
private:
Parent *parent;
public:
// constructor
Child(Parent *p) : parent(p) {}
// other members
};
//file:parent.h
#include "child.h"
class Parent
{
private:
Child child;
public:
// Constructor
Parent() : child(this) {}
// other members
};
How can the child gain access to the parent object's public members, keep the class definitions in separate files, and avoid the circular inclusion?