write a simple program for hierarchical inheritance in C++



The code for this program is as follows:

#include<iostream.h>
#include<conio.h>
class Multiply
{
protected:
int a;
public:
void get_digit(int x)
{
a=x;
}
};

class Square: public Multiply
{
public:
int get_square()
{
return(a*a);
}

};

class Cube: public Multiply
{
public:
int get_cube()
{
return(a*a*a);
}

};

void main()
{
clrscr();
Square s;
s.get_digit(3);
cout <<"Square:"<< s.get_square()<<endl;
Cube c;
c.get_digit(3);
cout <<"Cube:"<< c.get_cube()<<endl;
getch();
}

In the above example, we have three classes Multiply, Square, Cube. Class Multiply is inherited by both class Square and class Cube. In class Multiply, we have declared variable a in the protected mode, and defined a function void get_digit(int x); in public mode. In this function, we are assigning a=x means when this function is called then the value of x is assigned to the variable a. When the variables are declared in protected mode then only class which are inheriting the class, is able to access the variables. In this example variable a can be accessed by both class Square and class Cube.
In class Square, we have a function int get_square(). It will return the square value.
In class Cube, we have a function int get_cube(). It will return the cube value.
In main() method, we have created the object of Square class as shown below:
Square s;
After that by using this object first we have to call the get_digit(int x) method as shown below:
c.get_digit(3);
When this method will execute then the value of x will be assigned to a, such as a=3.
Now we are calling the method get_square(). This method will return the square value. Here we used
cout <<"Square:"<< s.get_square()<<endl;
This statement will give the following result:
Square:9
After this we have created the object of class Cube as shown below:
Cube c;
Now we are again calling the method int get_digit() as shown below:
c.get_digit();
Now we are calling the method int get_cube() as shown below:
c.get_cube(); this method return the cube value. Here we used
cout <<"Cube:"<< s.get_cube()<<endl;
This statement will give the following result:
Cube:27
Below is the output of the program:

Output

c++ program