Read OnLine Cpp Program Example



13 - POLYMORPHISM
PRAC 5  

// polymorphism example
// dynamic allocation and polymorphism
#include<iostream.h>
#include<conio.h>
class cpolygon
{
protected:
int width,height;
public:
void setvalues (int a,int b)
{
width=a;
height=b;
}
virtual int area(void)=0;
void printarea(void)
{
cout<<this->area()<<endl;
}
};
class crectangle:public cpolygon
{
public:
int area(void)
{
return(width*height);
}
};
class ctriangle:public cpolygon
{
public:
int area(void)
{
return(width*height/2);
}
};
void main()
{
clrscr();
cpolygon * ppoly1=new crectangle;
cpolygon * ppoly2=new ctriangle;
ppoly1->setvalues (4,5);
ppoly2->setvalues (4,5);
ppoly1->printarea();
ppoly2->printarea();
delete ppoly1;
delete ppoly2;
getch();
}
----OUTPUT----
20
10

 

Previous Next
Download