Lowest price ever! Learn Generative AI for 48% less!
Get my discount+ 2
Composition is a concept that applies to data members of a class (or struct). When you add a member to a class you have 2 choices: you have to decide if the relationship of the member to the class is one of composition or aggregation.
For example:
class School{};
class Human {
int age;
};
class Student : public Human {
School* school;
public:
SetSchool(School* school){this->school=school;}
}
The relationship of the 'age' member in the Human class is one of composition while the relationship of the 'school' member of the Student class is one of aggregation.
This can be seen by the fact that the 'age' member is an instance member of the class - if the class is destroyed the 'age' member is destroyed with the class instance.
OTOH if the Student object is destroyed, the actual School object the 'school' member is pointing to will not be automatically affected by the destruction of the Student object. The reason is that the School object is created outside the Student object and the Student object only refers to the School object by reference/pointer i.e. this relationship is one of aggregation.
So composition vs aggregation is really a comparison of different lifetime requirements: The lifetime of a member of a class in a composition relationship is tied to the lifetime of the 'owning' class object, while in an aggregation relationship the lifetime of the member (which must be a pointer or reference by definition!) is not tied to the lifetime of the owning class object.