How to implement child-parent aggregation link in C++?

Posted by Giorgio on Programmers See other posts from Programmers or by Giorgio
Published on 2012-10-03T14:40:19Z Indexed on 2012/10/03 15:50 UTC
Read the original article Hit count: 283

Filed under:
|

Suppose that I have

  • three classes P, C1, C2,
  • composition (strong aggregation) relations between P <>- C1 and P <>- C2, i.e. every instance of P contains an instance of C1 and an instance of C2, which are destroyed when the parent P instance is destroyed.
  • an association relation between instances of C1 and C2 (not necessarily between children of the same P).

To implement this, in C++ I normally

  • define three classes P, C1, C2,
  • define two member variables of P of type boost::shared_ptr<C1>, boost::shared_ptr<C2>, and initialize them with newly created objects in P's constructor,
  • implement the relation between C1 and C2 using a boost::weak_ptr<C2> member variable in C1 and a boost::weak_ptr<C1> member variable in C2 that can be set later via appropriate methods, when the relation is established.

Now, I also would like to have a link from each C1 and C2 object to its P parent object. What is a good way to implement this?

My current idea is to use a simple constant raw pointer (P * const) that is set from the constructor of P (which, in turn, calls the constructors of C1 and C2), i.e. something like:

class C1
{
  public:
    C1(P * const p, ...)
    : paren(p)
    {
    ...
    }

  private:
    P * const parent;
    ...
};

class P
{
  public:
    P(...)
    : childC1(new C1(this, ...))
    ...
    {
        ...
    }

  private:
    boost::shared_ptr<C1> childC1;
    ...
};

Honestly I see no risk in using a private constant raw pointer in this way but I know that raw pointers are often frowned upon in C++ so I was wondering if there is an alternative solution.

© Programmers or respective owner

Related posts about c++

Related posts about programming-practices