By using polymorphism, Define a class Shape having an attribute Area and a pure virtual function Calculate_Area. Also include following in this class. A constructor that initializes Area to zero. A method Display() that display value of member variable. Now derive two classes from Shape; Circle having attribute radius and Rectangle havingattributes Length and Breadth. Include following in each class. A constructor that takes values of member variables as argument. A method Display() that overrides Display() method of Shape class. A method Calculate_Area() that calculates the area as follows: Area of Circle= PI* Radius2 Area of Rectangle=Length*Breadth Use following driver program to test above classes.
int main() { Shape *p; Circle C1(5); Rectangle R1(4,6); p=&C1; p->Calculate_Area(); p->Display(); p=&R1; p->Calculate_Area(); p->Display(); return 0; }
#include <iostream>
using namespace std;
class Shape{
protected:
float Area;
public:
Shape(): Area(0){}
virtual void Calculate_Area(){}
virtual void Display(){}
};
class Circle: public Shape{
float radius;
const float PI = 3.14159265358979323846;
public:
Circle(float r): radius(r){}
void Calculate_Area(){
Area = PI * radius * radius;
}
void Display(){
cout<<"Area of Circle: "<<Area<<endl;
}
};
class Rectangle: public Shape{
float Length, Breadth;
public:
Rectangle(float l, float b): Length(l), Breadth(b){}
void Calculate_Area(){
Area = Length * Breadth;
}
void Display(){
cout<<"Area of Rectangle: "<<Area<<endl;
}
};
int main() {
Shape *p;
Circle C1(5);
Rectangle R1(4,6);
p=&C1;
p->Calculate_Area();
p->Display();
p=&R1;
p->Calculate_Area();
p->Display();
return 0;
}
Comments
Leave a comment