Composition

In this lesson, we'll learn how can we achieve composition in C++.

We'll cover the following

Composition is accessing other classes objects in your class and owner class owns the object and is responsible for its lifetime. Composition relationships are Part-of relationships where the part must constitute part of the whole object. We can achieve composition by adding smaller parts of other classes to make a complex unit.

So, what makes composition unique?

In composition, the lifetime of the owned object depends on the lifetime of the owner.

Example

A car is composed of an engine, tyres, and doors. In this case, a Car owned these objects so a Car is an Owner class and tyres,doors and engine classes are Owned classes.

Get hands-on with 1200+ tech skills courses.