C++ program to illustrate dynamic polymorphism using different shapes - Computer Programming

# Computer Programming

C C++ Java Python Perl Programs Examples with Output -useful for Schools & College Students

# Write a C++ program to illustrate dynamic polymorphism using different shapes as an example

Program:

#include<iostream.h>
class Circle;
class Rectangle;
class Square;
class Triangle;
class Trapezium;
class Area
{
protected:
float area;
public:
Area(float a)
{
area=a;
}
virtual void display(){}
};
class Circle:public Area
{
protected:
float ar;
public:
Circle(float a):Area( a)
{ar=3.14*a*a;}
void display()
{
cout<<"Area of Circle="<<ar;
}
};
class Rectangle:public Area
{
protected:
float ar;
public:
Rectangle(float a,float b):Area( a)
{ar=a*b;}
void display()
{
cout<<"Area of Rectangle="<<ar;
}
};
class Square:public Area
{
protected:
float ar;
public:
Square(float a):Area( a)
{ar=a*a;}
void display()
{
cout<<"Area of Square="<<ar;
}
};
class Triangle:public Area
{
protected:
float ar;
public:
Triangle(float a,float b):Area( a)
{ar=0.5*a*b;}
void display()
{
cout<<"Area of Triangle="<<ar;
}
};
class Trapezium:public Area
{
protected:
float ar;
public:
Trapezium(float a,float b):Area( a)
{ar=0.5*(a+b);}
void display()
{
cout<<"Area of Trapezium="<<ar;
}
};
int main()
{
int ra;
cin>>ra;
Circle c(ra);
cout<<"\nEnter length and breadth of rectangle:";
int a,b;
cin>>a>>b;
Rectangle r(a,b);
cout<<"Enter side of square:";
int sq;
cin>>sq;
Square s(sq);
cout<<"Enter height and base of circle:";
int h,ba;
cin>>h>>ba;
Triangle t(h,ba);
cout<<"Enter parallel sides's length of trapezium:";
int p,pt;
cin>>p>>pt;
Trapezium tr(p,pt);
Area *bptr[5];
bptr[0]=&c;
bptr[1]=&r;
bptr[2]=&s;
bptr[3]=&t;
bptr[4]=&tr;
bptr[0]->display();
bptr[1]->display();
bptr[2]->display();
bptr[3]->display();
bptr[4]->display();
return 0;

}

Sample Input and Output: