Lesson Overview and Goals

Hello, and welcome back! Today, we will delve into the fundamentals of Composition in C++! A crucial aspect of C++ design patterns, composition enables the construction of complex classes from simpler ones. In today's lesson, we will understand the concept of composition, its significance in software development, and how to implement it effectively in C++.

Garnering Clarity on the Composition Design Pattern

To kick-start our exploration, let's understand Composition. In object-oriented programming (OOP), composition allows a class to contain instances of other classes, facilitating the creation of complex systems from simple components. Take, for instance, building a car: independent objects like the engine, wheels, and seats are all brought together — a perfect example of composition in daily life. Under composition, if the parent object (the car) is destroyed, the child objects (the components) also cease to exist.

Acing the Composition Design in C++

Now, let's translate the theory into practical C++ code. Revisiting the car example, a Car class in C++ "composes" objects of the Engine, Wheels, and Seats classes. The Car class owns these child objects, meaning their existence is tied to the Car.

#include <iostream>
#include <string>

class Engine {
public:
    void start() {
        std::cout << "Engine starts" << std::endl;  // Engine start message
    }
    
    void stop() {
        std::cout << "Engine stops" << std::endl;   // Engine stop message
    }
};

class Wheels {
public:
    void rotate() {
        std::cout << "Wheels rotate" << std::endl;  // Wheel rotation message
    }
};

class Seats {
public:
    void adjust(const std::string& position) {
        std::cout << "Seats adjusted to position " << position << std::endl; // Seat adjustment message
    }
};

class Car {
private:
    Engine engine;
    Wheels wheels;
    Seats seats;
    
public:
    void start() {
        engine.start();    // Call to start engine
        seats.adjust("upright");   // Adjust seat position
        wheels.rotate();   // Get wheels rolling
    }
};

int main() {
    Car myCar;
    myCar.start();    // Begin car functions

    /*
    Output:
    Engine starts
    Seats adjusted to position upright
    Wheels rotate
    */
    return 0;
}

In the code above, the Car class encapsulates Engine, Wheels, and Seats objects, which operate independently but are part of the Car class, demonstrating the Composition pattern.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal