C++ Program to find cube of a number using virtual function


In this program, You will learn how to find cube of a number using virtual function in C++.


virtual void msg(){ }


Example: How to find cube of a number using virtual function in C++

Run it Now
#include<iostream>
using namespace std;

class First {
public:

   virtual void msg() {
       cout << "Welcome";
   }

   virtual void print() {
       cout << "Cube is :";
   }
};

class Second : public First {
   int n, c;
public:

   void msg() {
       cout << "Enter a Number :";
       cin>>n;
   }

   void print() {
       c = n * n * n;
       cout << "\nCube of a Number is :" << c;
   }
};

int main() {

   First *f;
   Second s;
   f = &s;
   f->msg();
   f->print();

   return 0;
}

Output:

Enter a Number :4
Cube of a Number is :64