Multilevel Inheritance in C++



Multilevel inheritance is a type of inheritance, where a class is derived from another derived class, creating a chain of inheritance that allows it to pass down its properties and behaviors through multiple levels of classes or inherit from its predecessor.

Implementing Multilevel Inheritance

To implement multilevel inheritance, define classes in a hierarchical manner, where one class inherits from another.

Syntax

The syntax of multilevel inheritance in C++ −

 class baseClass { //Here's a base class members }; class derivedClass1 : public baseClass { // Members of derivedClass1 }; class derivedClass2 : public derivedClass1 { // Members of derivedClass2 }; 

Here,

  • baseClass is the top-level class from where other classes derive.
  • derivedClass1 is the class that inherits from baseClass.
  • derivedClass2 Inherits from derivedClass1, creating a multilevel structure.

Block Diagram of Multilevel Inheritance

See the below block diagram demonstrating multilevel inheritance −

C++ Multilevel Inheritance

As per the above diagram, "Shape" is the base class, and it is deriving over to "Polygon" class, and "Polygon" class is further deriving over "Triangle" class in order to implement multilevel inheritance.

Example of Multilevel Inheritance

In the following example, we are implementing multilevel inheritance −

 #include <iostream> using namespace std; // Base class class Shape { public: void display() { cout << "This is a shape." << endl; } }; // First derived class class Polygon : public Shape { public: void sides() { cout << "A polygon has multiple sides." << endl; } }; // Second derived class class Triangle : public Polygon { public: void type() { cout << "A triangle comes under a three-sided polygon." << endl; } }; int main() { Triangle myTriangle; myTriangle.display(); // From Shape myTriangle.sides(); // From Polygon myTriangle.type(); // From Triangle return 0; } 

Output

 This is a shape. A polygon has multiple sides. A triangle comes under a three-sided polygon. 

Explanation

  • Firstly, a base class named Shape has been created with a public method display(), which prints "This is a shape."
  • Next, the first derived class named Polygon inherits from the Shape (or base class), meaning it gains access to the members of the Shape class, including the display()
  • The second derived class, named Triangle, inherits from the Polygon class, which allows Triangle to use both display() and sides() methods.

Main Function

  • An instance of a Triangle named myTriangle is created.
  • display() will first access the display() method by calling the Triangle class and then the Shape class because of inheritance.
  • Similarly, sides() will inherit from sides() of the Polygon class,
  • and myTriangle.type() from type() of Triangle class
Advertisements
close