Answer to Question #213133 in C++ for Hemambar

Question #213133

Create a base class called Shape which has two double type values. Use member functions get()

and set() to get and set the values. Use a virtual function display_area() to display the area. Derive

two specific classes called Triangle and Rectangle from the base class Shape. Redefine

display_area() in the derived classes. Write a program to display the rectangle or triangle area.


1
Expert's answer
2021-07-17T10:42:18-0400
#include <iostream>
#include <cmath>

using namespace std;

class Shape
{
private:
    double length,width;
public:
    Shape(double a, double b) {
        length = a;
        width = b;
    }
    double getLength() {return length; }
    double getWidth() {return width; }
    void setLength(double a) {length = a;}
    void setWidth(double  b) {width = b;}

    virtual void display_area() {cout << length * width;}
};
class Triangle : public Shape {
private:
    double c;
public:
    Triangle(double a, double b, double bar) : Shape(a, b) { c = bar;}

    void display_area() {
        double p = (this->getLength()+ this->getWidth()+c)/2;
        double area = sqrt(p*(p-this->getWidth())*(p-this->getLength())*(p-c));
        cout << "Area of the triangle: " << area << '\n';
    }
};

class Rectangle : public Shape
{
public:
    Rectangle(double a, double b) : Shape(a, b) {}

    void display_area() {
        cout << "The area of the rectangle: " << this->getLength()*this->getWidth() << '\n';
    }
};

int main()
{
    Triangle triangle = Triangle(3,4,5);
    triangle.display_area();

    Rectangle rect = Rectangle(3,4);
    rect.display_area();

    return 0;
}

Output:
Area of the triangle: 6
The area of the rectangle: 12

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
APPROVED BY CLIENTS