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

Latest

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

Friday, September 1, 2017

C++ program to illustrate dynamic polymorphism using different shapes

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()
{
cout<<"\nEnter radius of circle:";
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:

Enter radius of circle: 2
Enter length and breadth of rectangle: 4 6
Enter side of square: 2
Enter height and base of circle: 3 2
Enter parallel sides's length of trapezium: 3 3
Area of circle=12.56
Area of rectangle=24
Area of square=4
Area of triangle=3
Area of Trapezium=1.5

No comments:

Post a Comment