Write a program in C++ for to illustrate virtual functions - WAY2IT

Latest Post :

Home Top Ad

Write a program in C++ for to illustrate virtual functions



Command to be Used :-

1. Virtual functions
2. Pointer
3. Reference Operator


Code :-

#include <iostream.h>
#include<conio.h>
class CPolygon {
protected:
int width, height;
public:
void set_values (int a, int b)
{ width=a; height=b; }
virtual int area ()=0;
};
class CRectangle: public CPolygon {
public:
int area ()
{ return (width * height); }
};
class CTriangle: public CPolygon {
public:
int area ()
{ return (width * height / 2); }
};
void main () {
clrscr();
CRectangle rect;
CTriangle trgl;
CPolygon * ppoly1 = &rect;
CPolygon * ppoly2 = &trgl;
ppoly1->set_values (4,5);
ppoly2->set_values (4,5);
cout<<"Area of Rectangle :";
cout << ppoly1->area() << endl;
cout<<"Area of Triangel :";
cout << ppoly2->area() << endl;
getch();
}


Output :-