OOP: COMPOSITION AND RELATIONSHIPS
Has-A vs Is-A
The first design decision is whether a relationship is is-a or has-a.
Is-A Relationship
Use inheritance when one class is a specialized type of another class.
class Animal { };
class Dog : public Animal { };
This sentence is true:
A dog is an animal.
So public inheritance can make sense.
Has-A Relationship
Use composition or another object relationship when one class contains, uses, or refers to another class.
class Engine { };
class Car {
private:
Engine engine;
};
This sentence is true:
A car has an engine.
This sentence is false:
A car is an engine.
So Car : public Engine would be bad design.
Complete Example
#include <iostream>
using namespace std;
class Engine {
public:
void start() const {
cout << "Engine started" << endl;
}
};
class Car {
private:
Engine engine;
public:
void drive() const {
engine.start();
cout << "Car is driving" << endl;
}
};
class Animal {
public:
void breathe() const {
cout << "Animal is breathing" << endl;
}
};
class Dog : public Animal {
public:
void bark() const {
cout << "Dog is barking" << endl;
}
};
int main() {
Car car;
car.drive();
Dog dog;
dog.breathe();
dog.bark();
return 0;
}
Quick Decision Test
Say the relationship out loud:
| Sentence | Relationship |
|---|---|
| A dog is an animal. | inheritance |
| A car has an engine. | composition |
| A library has books. | composition |
| A student is a person. | inheritance |
| An order uses a payment service. | dependency |
Viva Answer
Use inheritance for an is-a relationship where the derived class is a specialized form of the base class. Use composition or another object relationship for has-a or uses-a relationships, where one class owns, contains, refers to, or temporarily uses another object.
Quick Check
- Is
Car : public Enginegood design? - What relationship does
Dog : public Animalrepresent? - What question should you ask before using inheritance?