D
Denis Remezov
[snip]fog said:Given:
class A;
and B "has-a" A. The composition relationship between A and B can be
implemented in three ways:
As Claudio remarked, #1 is composition, #2 is not; #3, well, #3 still
can model composition, and in many cases, technically, it's the only way
to go. It's just not required to necessarily represent composition.
Which method is better design?
It depends on what you need to do.
#1: B makes copies of components A or constructs new ones, who will die
just before itself. If this is the exact intent, then #1 is the right
choice. Class A must be a complete type at the point of definition of B.
You may want to avoid this scheme if, e.g., objects A exist elsewhere,
get cloned just for the purpose of becoming components of B, and are big
and expensive to copy. A's lifetime coincides (up to the finer details of construction/destruction)
with that of its host B.
#2: Components A must be created elsewhere. B should require a guarantee
that A doesn't get destructed prematurely, or some form of mechanism to
ensure that (e.g. reference counting). Type A can be incomplete where
B is defined. Components A cannot be re-assigned or re-created. Objects
of B cannot be default-constructed. A is created before B and should live
longer or at least as long. It can be shared between multiple objects
of B.
#3: The most general scheme, it can model #1 but at the cost of the
inconveience of a pointer and overhead of manual handling/freestore
allocation. It can imitate #2 with a slight syntactic difference.
If #1 or #2 fit you perfectly then use them.
Use this one if you need more choices:
B and A can be coupled quite loosely, their lifetimes can overlap in any
combination. Components A can be destructed, re-assigned or re-created.
They can be shared between multiple objects of B. B can be default
constructed. As in #2, you need to make sure component A is valid for
as long as B is using it. Type A can be incomplete where B is defined.
It can also be a polymorphic base class, e.g. an abstract class, with
all possibilities that are unavailable in #1.
Denis