To write a C++ program to illustrate dynamic polymorphism using different shapes as an example.

Program Algorithm:
Step 1: Make a class area which has a method.
Step 2: Make subclasses to this which have constructors that will take in the value for the required fields and will compute the area and put it in one of the member variables.
Step 3: call the method defined in step 1, which is overridden in all the subclasses to show their respective areas.

Program Code:
#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 Inputs and Outputs:
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
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: