AIM:
To implement a C++ program to add and subtract two numbers using polymorphism
To implement a C++ program to add and subtract two numbers using polymorphism
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:
#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: ";