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: 286
c++
|programming-practices
Suppose that I have
- three classes
P
,C1
,C2
, - composition (strong aggregation) relations between
P <>- C1
andP <>- C2
, i.e. every instance ofP
contains an instance ofC1
and an instance ofC2
, which are destroyed when the parentP
instance is destroyed. - an association relation between instances of
C1
andC2
(not necessarily between children of the sameP
).
To implement this, in C++ I normally
- define three classes
P
,C1
,C2
, - define two member variables of
P
of typeboost::shared_ptr<C1>
,boost::shared_ptr<C2>
, and initialize them with newly created objects inP
's constructor, - implement the relation between
C1
andC2
using aboost::weak_ptr<C2>
member variable inC1
and aboost::weak_ptr<C1>
member variable inC2
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