Simple Program for Multilevel Inheritance in C++


In the Multilevel Inheritance, there is one base class and another class which is derived from this base class is called derived class. The process continues to derive a new class from the derived class. The following is the schematic representation.Class A is the base class and class B is the class derived from class A.

Again class C is derived from class B and hence again class B is the base class and class C is the derived class. Have a look at the following example. As you can see, grandmother is the base class, Mother is the derived class and Daughter is the newly derived class from the existing derived class.

Simple Example of Multilevel Inheritance in C++

#include<iostream> using namespace std; class Student{ protected: int marks; public: void accept(){ cout<<" Enter marks"; cin>>marks; } }; class Test :public Student{ protected: int p=0; public: void check(){ if(marks>60){ p=1; } } }; class Result :public Test{ public: void print(){ if(p==1) cout<<"\n You have passed"; else cout<<"\n You have not passed"; } }; int main(){ Result r; r.accept(); r.check(); r.print(); return 0; }

Output:-

Enter marks 70
You have passed

Explanation of the program

As you can see there are three different classes that have been used such as the class Student, class Test and class result. Here the class student is inherited in class test whereas class Test is inherited in the class Result. The members of class Students can be accessed by the other two classes. As we have created only one object for result class Result this means that we can access all members from the other two classes. this is called multilevel inheritance.