Write a C++ Program to demonstrate an Example of Multilevel Inheritance. Here’s a Simple C++ Program to demonstrate an Example of Multilevel Inheritance in C++ Programming Language.
It has been discussed so far that a class can be derived from a class.
C++ also provides the facility of multilevel inheritance, according to which the derived class can also be derived by an another class, which in turn can further be inherited by another and so on.
The following example will illustrate the meaning of the multilevel inheritance:
The class D1 that is called first level of inheritance, inherits the class B. The derived class D1 is further inherited by the class D2, which is called second level of inheritance.
Below is the source code for C++ Program to demonstrate an Example of Multilevel Inheritance which is successfully compiled and run on Windows System to produce desired output as shown below :
SOURCE CODE : :
/* C++ Program to demonstrate an Example of Multilevel Inheritance */
#include<iostream>
using namespace std;
class Base
{
protected:
int b;
public:
void EnterData( )
{
cout << "\n Enter the value of b: ";
cin >> b;
}
void DisplayData( )
{
cout << "\n b = " << b;
}
};
class Derive1 : public Base
{
protected:
int d1;
public:
void EnterData( )
{
Base:: EnterData( );
cout << "\n Enter the value of d1: ";
cin >> d1;
}
void DisplayData( )
{
Base::DisplayData();
cout << "\n d1 = " << d1;
}
};
class Derive2 : public Derive1
{
private:
int d2;
public:
void EnterData( )
{
Derive1::EnterData( );
cout << "\n Enter the value of d2: ";
cin >> d2;
}
void DisplayData( )
{
Derive1::DisplayData( );
cout << "\n d2 = " << d2;
}
};
int main()
{
Derive2 objd2;
objd2.EnterData( );
objd2.DisplayData( );
return 0;
}
OUTPUT : :
/* C++ Program to demonstrate an Example of Multi level Inheritance */
Enter the value of b: 4
Enter the value of d1: 5
Enter the value of d2: 6
b = 4
d1 = 5
d2 = 6
Process returned 0
Above is the source code and output for C++ Program to demonstrate an Example of Multi level Inheritance which is successfully compiled and run on Windows System to produce desired output.
Multilevel Inheritance
The class D1 that is called first level of inheritance, inherits the class B. The derived class D1 is further inherited by the class D2, which is called second level of inheritance.
Below is the source code for C++ Program to demonstrate an Example of Multilevel Inheritance which is successfully compiled and run on Windows System to produce desired output as shown below :
SOURCE CODE : :
OUTPUT : :
Above is the source code and output for C++ Program to demonstrate an Example of Multi level Inheritance which is successfully compiled and run on Windows System to produce desired output.
need an explanation for this answer? contact us directly to get an explanation for this answer