Hierarchical inheritance in C++
Program 1
out put
In the above program, there is only one base class named A. derived classes B, C and D inherit all properties from A.
Derived classes(B, C and D) have their own properties as well as base class properties
Explanation above program
#include <iostream> //header file
using namespace std;
class A //paranr class A
{ // Start of class A
public:
int k,l;// assign two variables for int
void values() // create function for class A
{
k=6;
l=5;
}
}; // end of classA
class B:public A
{ // Start of class B
public:
void add() // create function for class B
{
cout << “The sum of k,l is:”<<k+l<< endl;
}
};// end of class B
class C:public A
{ // Start of class C
public:
void sub()// create function for class C
{
cout << “The sub of k,l is:”<<k-l<< endl;
}
};// end of class C
class D:public A
{// Start of class
public:
void mul() // create function for class D
{
cout << “The mul of k,l is:”<<k*l<< endl;
}
};// end of class
int main()
{
B obj1; // create object for class B
C obj2;// create object for class C
D obj3;// create object for class D
obj1.values(); //call values function through obj1
obj1.add(); //call add function through obj1
obj2.values(); //call values function through obj2
obj2.sub();//call add function through obj2
obj3.values(); //call values function through obj3
obj3.mul();//call add function through obj3
return 0;
}