C++ Multilevel Inheritance
Multilevel Inheritance
A class can also be derived from one class, which is already derived from another class.
In the Inheritance chapter, the Car class inherited from the Vehicle class. In the following example, SportsCar is derived from Car (which is derived
from Vehicle).
Example
// Base class (parent)
class Vehicle {
public:
void honk() {
cout << "Tuut, tuut!\n";
}
};
// Derived class (child)
class Car : public Vehicle {
public:
void drive() {
cout << "Driving...\n";
}
};
// Derived class (grandchild)
class SportsCar : public Car {
public:
void turbo() {
cout << "Turbo on!\n";
}
};
int main() {
SportsCar myCar;
myCar.honk(); // From Vehicle
myCar.drive(); // From Car
myCar.turbo(); // From SportsCar
return 0;
}
Try it Yourself »
A SportsCar object can use the methods of all three classes: its own, the ones from Car, and the ones from Vehicle.