Header Ads

Composition vs. Aggregation In C++

Composition vs. Aggregation In C++ :

Composition is also known as “has-a” relationship. As you can see from the diagram below, a car "has-a" carburetor, or a car is "composed of" a carburetor. When the diamond is colored black it signifies composition, i.e. the object on the side closest to the diamond is made up of or contains the other object. While the white diamond signifies aggregation, which means that the object closest to the diamond can have or possess the other object.

Another way to distinguish between composition and aggregation in modeling the real world is to consider the relative lifetime of the contained object. For example, if a Car object contains a Chassis object, a Chassis will most likely not be replaced during the lifetime of the Car. It will have the same lifetime as the car itself; so the relationship is one
of composition.
On the other hand, if the Car object contains a set of Tire objects, these Tire objects may wear out and get replaced several times. Or if the Car becomes unusable, some Tires may be salvaged and assigned to another Car. At any rate, the Tire objects have different lifetimes than the Car object; therefore the relationship is one of aggregation.
If one were to make a C++ software Class to implement the relationships described above, the Car object would contain a complete Chassis object in a data member. This Chassis object would be instantiated in the constructor of the Car class (or defined as the data type of the data member and its properties assigned in the constructor.) And since it would be a wholly contained data member of the Car class, the Chassis object would no longer exist if a Car class object was to be deleted.
On the other hand, the Car class data members that point to Tire objects would most likely be C++ pointers. Tire objects could be instantiated and deleted externally, or even assigned to data members of a different Car object. Tire objects would have an independent lifetime separate from when the Car object was deleted.

[Source: Wikipedia]

No comments