Advertisement

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


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


virtual void msg(){ 
    //statement
}

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

#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 << "Cube 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