Answer to Question #199405 in C++ for Hunny

Question #199405

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; }




1
Expert's answer
2021-05-27T06:26:00-0400
#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; 
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog