Classes Composition in C++
Lesson Introduction and What is Composition?
Welcome to the lesson on class composition in C++. You have now learned the basics of classes, methods, constructors, and encapsulation. Today, we are going to take a step further into object-oriented programming by exploring class composition. The goal of this lesson is to understand how to construct complex classes by combining simpler, reusable components.
Class composition is an essential design principle that enables you to create complex objects. We will learn how to build classes containing other objects and see practical applications of this approach. Let's get started!
What is Composition? A real-life analogy would be a car. A car comprises various parts, such as an engine, wheels, and a transmission. These parts work together to make the car function. Similarly, in programming, composition allows you to build a Car class that includes an Engine class, a Wheel class, and so on.
Basic Class Composition
Let's start with a simple example to understand class composition:
In this example, the Car class contains an Engine object. Here's what's happening:
- The
Engineclass has a method calledstart(), which prints "Engine started". - The
Carclass has a private data memberengineof typeEngine. - The
Carclass also has astart()method that calls theEngine'sstart()method before printing "Car started".
When you create a Car object and call its start() method, it first starts the engine and then starts the car, showing how the Car uses functionality provided by the Engine.
Advanced Class Composition: Part 1
Now let's look at a more advanced example, where a Car is composed of both Engine and Wheel objects:
In this example, the Car class will have both Engine and Wheel objects. Here are some key points:
- The
Engineclass has a private attributehorsepowerand a methodgetHorsepower()to retrieve it. - The
Wheelclass has a private attributesizeand a methodgetSize()to retrieve it.
