Multilevel Inheritance
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 AnimalmyPuppy.bark(); // Inherited from DogmyPuppy.weep(); // Inherited from Puppyreturn 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:
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn C++ on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn C++
Learn C++ — a versatile programming language that’s important for developing software, games, databases, and more.Beginner Friendly11 hours