Dongle
Dongle

Reputation: 622

Understanding Composition and Aggregation

How can I identify Composition and Aggregation in code? specially when drawing class diagrams for existing code?

I know Composition is a 'HAS-A' relationship and aggregation is a 'PART OF' relationship. And I know in composition subclass instance will get destroyed with the class and in aggregation it is not.

Following is a C++/CLI code

Alarm.h

ref class Alarm
{
   public:
       Notification ^n;
       Alarm();
};

Alarm.cpp

Alarm::Alarm()
{
     n = gcnew Notification ();
}

According to my knowledge, the connection between Alarm and Notification is Composition, because without Alarm, there is no Notification. Am I correct? If I am correct, how can I make this code to have an aggregation relationship between two classes? Code example there please?

Please help.

Upvotes: 1

Views: 217

Answers (1)

Medinoc
Medinoc

Reputation: 6608

I think aggregation is when the aggregated object is somehow exposed directly (and the user is expected to access it), while composition would be entirely internal and independent of what the user code sees.

Which would make your example an aggregation.

Upvotes: 2

Related Questions