C++ Program to perform an arithmetic calculation using virtual function


In this program, You will learn how to perform arithmetic calculations using a virtual function in C++.


virtual void calculate() { 
   //statement
}

Example: How to perform an arithmetic calculation using a virtual function in C++.

#include<iostream>
using namespace std;

class First {
public:

   virtual void calculate() {
       cout << "Arithmetic calculation";
   }
};

class Second : public First {
public:

   int x, y, res;
   int ch;

   void calculate() {

       cout << "Enter 1 For Addition :";
       cout << "\nEnter 2 For Subtraction :";
       cout << "\nEnter 3 For Multiplication :";
       cout << "\nEnter 4 For Division :";
       cout << "\nEnter 5 For Mode :\n";
       cin >> ch;

       switch (ch) {
           case 1:
           {
               cout << "\nEnter Two Numbers :";
               cin >> x >> y;
               res = x + y;
               cout << "\nResult is :" << res;
               break;
           }
           case 2:
           {
               cout << "\nEnter Two Numbers :";
               cin >> x >> y;
               res = x - y;
               cout << "\nResult is :" << res;
               break;
           }
           case 3:
           {
               cout << "\nEnter Two Numbers :";
               cin >> x >> y;
               res = x * y;
               cout << "\nResult is :" << res;
               break;
           }
           case 4:
           {
               cout << "\nEnter Two Numbers :";
               cin >> x >> y;
               res = x / y;
               cout << "\nResult is :" << res;
               break;
           }
           case 5:
           {
               cout << "\nEnter Two Numbers :";
               cin >> x >> y;
               res = x % y;
               cout << "\nResult is :" << res;
               break;
           }
           default:
           cout<<"\nInvalid selection";
       }
   }
};

int main() {

   First *f;
   Second s;
   f = &s;
   f->calculate();
   return 0;
}

Output:

Enter 1 For Addition :
Enter 2 For Subtraction :
Enter 3 For Multiplication :
Enter 4 For Division :
Enter 5 For Mode :
2

Enter Two Numbers :10 5

Result is :5