Multi-level inheritance in C++ language
In this tutorial, we will discuss an Oop concept of the multi-level inheritance in C++ language.
In the diagram below, class C inherits class B and class B inherits class A which means class C is the child of class B and class B is the child to class A.
Program 1
#include <iostream> #include <conio.h> using namespace std; class Base{ public: void display1(){ cout<<"I am base class"<<endl; } }; class Intermediate: public Base{ public: void display2(){ cout<<"I am an intermediate class"<<endl; } }; class derived: public Intermediate{ public: void display3(){ cout<<"I am derived class"<<endl; } }; int main() { derived obj; obj.display1(); obj.display2(); obj.display3(); getch(); return 0; }
The above code is executed, it produces the following result
I am base class I am an intermediate class I am derived class
Program 2
Explanation of above program
#include <iostream>
using namespace std;
class A //class A
{ // start of class A
public: //public section in class A
int x,y; //assign two variables x,y
void values()
{
x=12; //assign value for x
y=18; //assign value for y
}
}; // end of class A
class B:public A //inherit properties B from A
{ // start of class B
public: //public section in class B
void add(){ //function add
cout << “The result of x+y is ” << x+y<<endl;
// display statement output of x+y
}
}; // end of class B
class C:public B //inherit properties C from B
{
public: //public section in class C
void sub() //function sub
{
cout << “The result of x-y is ” << x-y<<endl;
// display statement output of x-y
}
};
class D:public C//inherit properties D from C
{// start of class C
public: //public section in class D
void mul() //function mul
{
cout << “The result of x*y is ” << x*y<<endl;
// display statement output of x*y
}
}; // end of class C
int main() // main section
{
D obj; //object for class D(child classs)
obj.values(); //called function value through object
obj.add(); //called function add through object
obj.sub(); //called function sub through object
obj.mul();//called function mul through object
return 0;
}