Write a C++ program to add and subtract two numbers using polymorphism.




Program Algorithm:
Step 1: Include the header files
Step 2: Declare the base class base
Step 3: Declare and define the function setVar() and getresult()
Step 4: Create a pure virtual function op ()
Step 5: Create two derived classes add and sub from base class
Step 6: Declare the virtual function op ()
Step 7: Create an object pointer for base class
Step 8: Create an object for derived classes and access the member functions to find the result.




Program Code in C++:
#include <iostream.h>
using namespace std;
// abstract base class
class base
{
protected: // attribute section
int num1;
int num2;
int result;
public: // behavior section
void setVar(int n1,int n2)
{
num1 = n1;
num2 = n2;
}
virtual void op() = 0; // pure virtual function
int getresult() 
{
return result;
}
};
class add: public base // add class inherits from base class
{
public:
void op() 
{
result = num1 + num2;
}
};
//sub class inherit base class
class sub: public base
{
public:
void op() 
{
result = num1 - num2;
}
};
int main()
{
int x,y;
base *m; //pointer variable declaration of type base class
add ad; //create object1 for addition process
sub su; //create object2 for subtraction process
cout << "\nEnter two numbers separated by space, or press Ctrl+z to Exit: ";
while(cin >> x >> y)
{
m = &ad;
m->setVar( x , y );
m->op(); //addition process, even though call is on pointer to base!
cout << "\nResult of summation = " << m->getresult();
m = &su;
m->setVar( x , y );
m->op(); //subtraction process, even though call is on pointer to base!
cout << "\nResult of subtraction = " << m->getresult() << endl << endl;
cout << "\nEnter two numbers seperated by space :";
}
return 0;
}





Program Output:
Enter two numbers separated by space: 70 50
Result of summation = 120
Result of subtraction = 20
Mukesh Rajput

Mukesh Rajput

I am a Computer Engineer, a small amount of the programming tips as it’s my hobby, I love to travel and meet people so little about travel, a fashion lover and love to eat food, I am investing a good time to keep the body fit so little about fitness also..

Post A Comment:

0 comments: