Home »
C++ programs »
C++ inheritance programs
C++ program to demonstrate example of hierarchical inheritance to get square and cube of a number
Learn about the hierarchical inheritance in C++, and implement a C++ program using the hierarchical inheritance.
[Last updated : March 02, 2023]
Hierarchical Inheritance in C++
In C++, hierarchical inheritance is defined as the inheritance that has a hierarchical structure of classes, in which a single base class can have multiple derived classes, and other subclasses can also inherit these derived classes.
This program will demonstrate example of hierarchical inheritance to get square and cube of a number in c++ programming language.
Hierarchical inheritance to get square and cube of a number program in C++
/*
C++ program to demonstrate example of hierarchical inheritance
to get square and cube of a number.
*/
#include <iostream>
using namespace std;
class Number {
private:
int num;
public:
void getNumber(void)
{
cout << "Enter an integer number: ";
cin >> num;
}
//to return num
int returnNumber(void)
{
return num;
}
};
//Base Class 1, to calculate square of a number
class Square : public Number {
public:
int getSquare(void)
{
int num, sqr;
num = returnNumber(); //get number from class Number
sqr = num * num;
return sqr;
}
};
//Base Class 2, to calculate cube of a number
class Cube : public Number {
private:
public:
int getCube(void)
{
int num, cube;
num = returnNumber(); //get number from class Number
cube = num * num * num;
return cube;
}
};
int main()
{
Square objS;
Cube objC;
int sqr, cube;
objS.getNumber();
sqr = objS.getSquare();
cout << "Square of " << objS.returnNumber() << " is: " << sqr << endl;
objC.getNumber();
cube = objC.getCube();
cout << "Cube of " << objS.returnNumber() << " is: " << cube << endl;
return 0;
}
Output
Enter an integer number: 10
Square of 10 is: 100
Enter an integer number: 20
Cube of 10 is: 8000