Sunday, February 7, 2016

POLYMORPHISM

AIM:
         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: ";

     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 or press Ctrl+z to Exit: ";
    }
    return 0;
}

SAMPLE OUTPUT:

Enter two numbers separated by space, or press Ctrl+z to Exit: 88  9
Result of summation = 97
Result of subtraction = 79


Enter two numbers separated by space or press Ctrl+z to Exit: ^Z

Process returned 0 (0x0) execution times: 102.711 s
Press any key to continue.
*/

RESULT:
                Thus a C++ program to add and subtract two numbers using polymorphism is implemented successfully.


No comments:

Post a Comment