Composition is a design principle in object-oriented programming where a class contains objects of other classes as part of its state. It models a “has-a” relationship, meaning one class is composed of one or more objects from other classes.
In composition, the lifetime of the part objects is tied to the lifetime of the whole object. When the containing object is destroyed, its parts are also destroyed.
#include <iostream>
#include <string>
class Engine {
public:
void start() {
std::cout << "Engine started." << std::endl;
}
};
class Car {
private:
Engine engine; // Car has an Engine
std::string model;
public:
Car(const std::string& m) : model(m) {}
void start() {
engine.start(); // Delegating start to Engine
std::cout << "Car model: " << model << " is ready to go!" << std::endl;
}
};
int main() {
Car myCar("Toyota");
myCar.start();
return 0;
}
#include <iostream>
#include <vector>
#include <string>
class Book {
public:
std::string title;
Book(const std::string& t) : title(t) {}
};
class Library {
private:
std::vector<Book*> books; // Library has Books (Aggregation)
public:
void addBook(Book* book) {
books.push_back(book);
}
void showBooks() {
for (const auto& book : books) {
std::cout << "Book: " << book->title << std::endl;
}
}
};
int main() {
Book book1("1984");
Book book2("Brave New World");
Library library;
library.addBook(&book1);
library.addBook(&book2);
library.showBooks();
return 0;
}