C++ Program to perform arithmetic calculation using virtual function


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


virtual void calculate() { }


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

Run it Now
#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 << "\nEnter 1 For Addition :";
       cout << "\nEnter 2 For Subtraction :";
       cout << "\nEnter 3 For Multiplication :";
       cout << "\nEnter 4 For Division :";
       cout << "\nEnter 5 For Mode :";
       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 :1
Enter 2 For Subtraction :
Enter 3 For Multiplication :
Enter 4 For Division :
Enter 5 For Mode :
Enter Two Numbers :6 2
Result is :8