Write a C++ program to explain virtual function (polymorphism) by creating a base class c_polygon which has virtual function area(). Two classes c_rectangle and c_traingle derived from c_polygon and they have area() to calculate and return the area of rectangle and triangle respectively.





Implementation of the above problem:
#include<iostream.h>
#include<conio.h>
class c_polygon
{
protected:
float a,b;
public:
void get_data()
{
cout<<"\nEnter any two floating values:\n";
cin>>a>>b;
}
virtual float area()
{
return 0;
}
};
class c_rectangle:public c_polygon
{
public:
float area()
{
return (a*b);
}
};
class c_triangle:public c_polygon
{
public:
float area()
{
return (b*a/2);
}
};
void main()
{

clrscr();
c_rectangle r;
c_triangle t;
c_polygon *p;
p=&r;
p->get_data();
cout<<"\nArea of rectangle is "<<p->area();
p=&t;
p->get_data();
cout<<"\nArea of triangle is "<<p->area();
getch();
}





Thanks
Mukesh Rajput
Mukesh Rajput

Mukesh Rajput

I am a Computer Engineer, a small amount of the programming tips as it’s my hobby, I love to travel and meet people so little about travel, a fashion lover and love to eat food, I am investing a good time to keep the body fit so little about fitness also..

Post A Comment:

0 comments: