OOP: COMPOSITION AND RELATIONSHIPS
Composition
Composition means one class owns another object as a part of itself.
Simple idea:
Whole owns part.
Part lifetime depends on whole.
Example:
Car has Engine
House has Rooms
Library has Books
Complete Example
#include <iostream>
#include <string>
#include <utility>
using namespace std;
class Engine {
private:
string model;
public:
explicit Engine(string engineModel) : model(move(engineModel)) {}
void start() const {
cout << model << " engine started" << endl;
}
};
class Car {
private:
Engine engine;
public:
Car(string engineModel) : engine(move(engineModel)) {}
void drive() const {
engine.start();
cout << "Car is moving" << endl;
}
};
int main() {
Car car("Hybrid");
car.drive();
return 0;
}
Output:
Hybrid engine started
Car is moving
Ownership and Lifetime
In the example:
CarownsEngine.Engineis a data member insideCar.- When
Caris created, itsEngineis created. - When
Caris destroyed, itsEngineis destroyed automatically.
This is strong ownership.
Why Composition Is Often Preferred
Composition is often better than inheritance because:
- It avoids deep inheritance chains.
- It keeps classes focused.
- It makes code easier to change.
- It models
has-arelationships clearly. - It supports encapsulation because the part can stay private.
Viva Answer
Composition is a strong has-a relationship where one class owns another object as a member. The contained object's lifetime is controlled by the containing object. For example, a Car has an Engine.
Quick Check
- In composition, who owns the part object?
- What happens to the part when the whole object is destroyed?
- Why is composition better than inheritance for
CarandEngine?