Multilevel Inheritance

raghavtandulkar's avatar
Published Feb 5, 2025
Contribute to Docs

Multilevel inheritance is an Object-Oriented Programming (OOP) concept where a class can inherit properties and methods from a class that is already inherited from another class, forming a hierarchical class structure. This forms a parent-child-grandchild relationship between classes, enabling the creation of specialized classes from existing ones.

Syntax

In C++, multilevel inheritance follows this syntax:

class BaseClass {
    // Base class members
};

class DerivedClass1 : AccessSpecifier BaseClass {
    // First level derived class members
};

class DerivedClass2 : AccessSpecifier DerivedClass1 {
    // Second level derived class members
};

Example

In the following example, multilevel inheritance is demonstrated where Puppy inherits from Dog, which in turn inherits from Animal, allowing Puppy to access methods from both Dog and Animal:

#include <iostream>
using namespace std;
class Animal {
public:
void eat() {
cout << "Animal is eating." << endl;
}
};
class Dog : public Animal {
public:
void bark() {
cout << "Dog is barking." << endl;
}
};
class Puppy : public Dog {
public:
void weep() {
cout << "Puppy is weeping." << endl;
}
};
int main() {
Puppy myPuppy;
myPuppy.eat(); // Inherited from Animal
myPuppy.bark(); // Inherited from Dog
myPuppy.weep(); // Inherited from Puppy
return 0;
}

The output of the above code will be:

Animal is eating.
Dog is barking.
Puppy is weeping.

Codebyte Example

The following example demonstrates how multilevel inheritance allows a class to inherit features across multiple levels, forming a structured class hierarchy:

Code
Output
Loading...

All contributors

Contribute to Docs

Learn C++ on Codecademy