Object-Oriented Programming – How to Reach the Parent Object in C++

ccompositionobject-oriented

I have a parent object that has some other objects as fields. The parent object fully owns these fields: they can be declared as fields of the parent object (MyPart part), directly, not as references.

I would prefer to initialize these fields in constructor, but in some cases they do need to reach the parent object instance and call methods on it as they work. With raw pointers, I could simply pass this to they constructors or setters. I have just discovered however that creating smart pointer from this is something near impossible, because such pointer would not know when the parent object goes out of scope (for sure not where the constructor returns!). But I do known that being the fields of the parent object, these children definitely cannot outlive it.

The only "clean" idea I can so far imagine is to construct the object in some factory method where reference to the constructed parent can be a smart pointner, then construct children separately and use the setter to compose the parent. Is this really the best approach?

As we have now policy to avoid raw pointers at all costs, what other options could I have? Or just using raw pointers in such a case is appropriate?

Best Answer

You can use a reference to the parent. As a sketch

class Parent;

class Child {
private: 
    Parent & parent;
public:
    Child(Parent & p) : parent(p) {}
    // other members
};

class Parent {
private:
    Child child;
public:
    Parent() : child(*this) {}
    // other members
};

As a bonus, the compiler will refuse to let you construct a Child without a Parent. You can go further, and make Child only privately constructable, and friend Parent.