Multilevel inheritance

Multilevel inheritance is a type of inheritance where a class is derived from another derived class, creating a chain of inheritance.

Syntax

class Base {
    // Base class members
};

class Intermediate : public Base {
    // Intermediate class members
};

class Derived : public Intermediate {
    // Derived class members
};

Example

#include <iostream>
using namespace std;

class Animal {
public:
    void eat() {
        cout << "Eating..." << endl;
    }
};

class Mammal : public Animal {
public:
    void breathe() {
        cout << "Breathing..." << endl;
    }
};

class Dog : public Mammal {
public:
    void bark() {
        cout << "Barking..." << endl;
    }
};

int main() {
    Dog myDog;
    myDog.eat();    // Inherited from Animal
    myDog.breathe(); // Inherited from Mammal
    myDog.bark();   // Specific to Dog
    return 0;
}

Key Points

  1. Hierarchy: Multilevel inheritance creates a hierarchy of classes, where each class inherits from the class above it.
  2. Transitive: Attributes and methods are passed down through the hierarchy.

Example of Multilevel Inheritance Usage

#include <iostream>
using namespace std;

class Vehicle {
public:
    void start() {
        cout << "Vehicle started" << endl;
    }
};

class Car : public Vehicle {
public:
    void drive() {
        cout << "Car is driving" << endl;
    }
};

class SportsCar : public Car {
public:
    void accelerate() {
        cout << "Sports car accelerating" << endl;
    }
};

int main() {
    SportsCar myCar;
    myCar.start();      // Inherited from Vehicle
    myCar.drive();      // Inherited from Car
    myCar.accelerate(); // Specific to SportsCar
    return 0;
}