0

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?

vishayp
  • 70
  • 5
  • Use forward declarations in the header files, and move all implementation to cpp files. See here: https://stackoverflow.com/questions/4757565/what-are-forward-declarations-in-c. – wohlstad Jun 20 '22 at 07:19
  • @wohlstad Thank you, I learned a few things from your comment. Coming from a C background, I was aware of forward declarations for functions, but not classes. Your link was helpful, I now see the "how" in how that works, but I am not sure that I see the "why". I also thought the initialization list was part of the constructor's function header and therefore the constructor's declaration, but I see the initialization list is considered part of the definition. – vishayp Jun 20 '22 at 07:53

0 Answers0