CJCoding With Joseph
15free / daySign inCreate account

Mastering C++

What is Composition?

Classes In C++

Composition is a key concept in object-oriented programming that lets one class contain objects from other classes, creating a "has-a" relationship

For example, a Car has an Engine, or a Library has Books. Composition allows us to create complex types by combining simpler ones, making our code more organized, reusable, and easier to maintain.


Composition - A

A simple example of composition is a Person class and an Address class, where a Person "has an" Address. Instead of placing address attributes directly in the Person class, we define a separate Address class. This way, if we create another class, such as a Shop class, we can also use the Address class to give the shop an address. Composition allows both Person and Shop to reuse the Address class since they both "have an" address.

Members only

Keep reading this lesson

You've reached the end of the free preview. Unlock the rest of this lesson plus 21 more lessons in Mastering C++.

  • Unlimited coding questions
  • Unlimited access to all classroom material
  • Weekly live call for questions and guidance
  • 3,000 AI tutor tokens / month
  • Personal SQL database (3 MB)
  • Progress tracking

Cancel any time.