Answer to Question #199394 in C++ for Root

Question #199394

By using inheritance, 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-27T07:18:01-0400


#include <iostream>


using namespace std;
class Shape{
    protected:
        double area;
    public:
        virtual void Calculate_Area()=0;
        Shape(){
            area=0;
        }
        void Display(){
            cout<<"\nArea is: "<<area;
        }
};
class Circle:public Shape{
    private:
        double radius;
    public:
        Circle(double r){
            radius=r;
        }
    void Display(){
    cout<<"\nRadius is: "<<radius;
}
    void Calculate_Area(){
        double pi=3.142;
        cout<<"\nArea of the Circle is: "<<pi*radius*radius;
    }
};
class Rectangle:public Shape{
    private:
        double length;
        double breadth;
    public:
        Rectangle(double l, double b){
            length=l;
            breadth=b;
        }
    void Display(){
        cout<<"\nLength is: "<<length;
        cout<<"\nBreadth is: "<<breadth;
    }
    void Calculate_Area(){
        cout<<"\nArea of the Rectangle is: "<<length*breadth;
    }
};
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