Knowee
Questions
Features
Study Tools

Write a C++ program to demonstrate hierarchical inheritance to get square and cube of a number.

Question

Write a C++ program to demonstrate hierarchical inheritance to get square and cube of a number.

🧐 Not the exact question you are looking for?Go ask a question

Solution

Sure, here is a simple C++ program that demonstrates hierarchical inheritance to get the square and cube of a number.

#include<iostream>
using namespace std;

// Base class
class Number {
   protected:
      int num;
   public:
      void getNumber(int n) {
         num = n;
      }
};

// First derived class
class Square : public Number {
   public:
      int getSquare() {
         return num * num;
      }
};

// Second derived class
class Cube : public Number {
   public:
      int getCube() {
         return num * num * num;
      }
};

int main() {
   Square sq;
   Cube cu;
   int number;

   cout << "Enter a number: ";
   cin >> number;

   sq.getNumber(number);
   cu.getNumber(number);

   cout << "Square of " << number << " is: " << sq.getSquare() << endl;
   cout << "Cube of " << number << " is: " << cu.getCube() << endl;

   return 0;
}

In this program, Number is the base class and Square and Cube are the derived classes. The base class has a member variable num and a function getNumber() to get the number from the user. The derived classes Square and Cube inherit the properties of the base class and have their own functions getSquare() and getCube() to calculate the square and cube of the number respectively.

This problem has been solved

Similar Questions

Write a programme in C++ which read and print employee information with department and pf information using hierarchical inheritance

The program must accept four integers a, b, c and d as input. The program must solve the equation b * c - (a + d) and print it as the output.

Write a program to prompt user for an integer and display a triangle of stars with the same height as the input provided by the user. For example:

Which of the following is not a type of inheritance? Hierarchical Distributive Multiple Multilevel

x = 462231238978z = 2c = x ^ x * z // 2print(c)what will be the output of this python code

1/1

Upgrade your grade with Knowee

Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.