Sunday, 29 April 2012

Program showing Polymorphism in C++


#include <iostream.h>

class H
{
public:
 int xc;
 int yc;
 void move(int, int);
 virtual void init(int, int);
};

void H::init(int ix, int iy)
{
 xc = ix;
 yc = iy;
}

void H::move(int nx, int ny)
{
 xc = xc + nx;
 yc = yc + ny;
}

class L : public H
{
public:
 int p;
 void q(int);
 virtual void init(int, int, int);
};

void L::q(int k)
{
 p = p - k;
}

 void L::init (int ix, int iy, int
            ks)
{
 xc = ix;
 yc = iy;
 p = ks;
}

int main()
{
 H V;
 V.init (12, 15);
 cout << "The X-location of the V is " <<
           V.xc << "\n";
 cout << "The Y-location of the V is " <<
           V.yc << "\n";
 V.move (34, 9);
 cout << "The new X-location of the V is " <<
           V.xc << "\n";
 cout << "The new Y-location of the V is " <<
           V.yc << "\n";

 L D;
 D.init (97,52,5);
 D.move (49,71);
 cout << "The new X-location of the D is " <<
           D.xc << "\n";
 cout << "The new Y-location of the D is " <<
           D.yc << "\n";
 cout << "The number of k initially is " <<
           D.p << "\n";
 D.q(3);
 cout << "The number of k left is " << D.p <<
           "\n";
 cout << "\nPress ENTER to continue..." << endl;
 getchar();
 return 0;
}

 
 


No comments:

Post a Comment