7

I'm beginning to study OOAD and I'm having difficulty finding a C++ code example that'd illustrate how Association, Aggregation and Composition are implemented programmatically. (There are several posts everywhere but they relate to C# or java). I did find an example or two, but they all conflict with my instructor's instructions and I'm confused.

My understanding is that in:

  • Association: Foo has a pointer to Bar object as a data member
  • Aggregation: Foo has a pointer to Bar object and data of Bar is deep copied in that pointer.
  • Composition: Foo has a Bar object as data member.

And this is how I've implemented it:

//ASSOCIATION
class Bar
{
    Baz baz;
};
class Foo
{
    Bar* bar;
    void setBar(Bar* _bar)
    {
        bar=_bar;
    }
};

//AGGREGATION
class Bar
{
    Baz baz;
};
class Foo
{
    Bar* bar;
    void setBar(Bar* _bar)
    {
        bar = new Bar;
        bar->baz=_bar->baz;
    }
};


//COMPOSTION
class Bar
{
    Baz baz;
};
class Foo
{
    Bar bar;
    Foo(Baz baz)
    {
        bar.baz=baz;
    }
};

Is this correct? If not, then how should it be done instead? It'd be appreciated if you also give me a reference of a code from a book (so that I can discuss with my instructor)

Talha5389
  • 179

1 Answers1

8

There are multiple ways to map the OO concepts of association, aggregation and composition to C++ code. This is especially true for aggregation, because there is not even a consensus what it exactly means.

Your mapping suggests the following semantics, which are not wrong:

  • Association: Foo has a pointer to Bar object as a data member, without managing the Bar object -> Foo knows about Bar
  • Composition: Foo has a Bar object as data member -> Foo contains a Bar. It can't exist without it.
  • Aggregation: Foo has a pointer to Bar object and manages the lifetime of that object -> Foo contains a Bar, but can also exist without it.

As stated, aggregation is the difficult one here because, even within UML, the meaning of aggregation is not crystal clear. Another possible meaning of aggregation is "Foo contains a Bar object that is shared with other objects." This would typically be represented in C++ code by means of a std::shared_pointer or boost::shared_pointer.
Which meaning your instructor attaches to aggregation must be discussed with him.