Computing Total Area of Multiple Shapes Using Polymorphism in C++

Define an abstract base class Shape and five derived classes: Circle, Square, Rectangle, Trapezoid, and Triangle. Use a virtual function to compute the area of each shape, then calculate their total sum. The program must use a base class pointer array, where each element points to an object of a derived class. Use PI = 3.1415926.

Input Format:

The input consists of a single line containing nine positive numbers, separated by spaces, in the following order: radius of the circle, side length of the square, width and height of the rectangle, upper base, lower base, and height of the trapeziod, and base and height of the triangle.

Output Format:

Print the total area of all shapes, rounded to three decimal places.

Sample Enput:

12.6 3.5 4.5 8.4 2.0 4.5 3.2 4.5 8.4

Sample Output:

total of all areas = 578.109
#include <iostream>
#include <vector>
#include <memory>
#include <iomanip>
using namespace std;

constexpr double PI = 3.1415926;

class Shape {
public:
    virtual ~Shape() = default;
    virtual double getArea() const = 0;
};

class Circle : public Shape {
    double radius;
public:
    Circle(double r) : radius(r) {}
    double getArea() const override {
        return PI * radius * radius;
    }
};

class Square : public Shape {
    double side;
public:
    Square(double s) : side(s) {}
    double getArea() const override {
        return side * side;
    }
};

class Rectangle : public Shape {
    double width, height;
public:
    Rectangle(double w, double h) : width(w), height(h) {}
    double getArea() const override {
        return width * height;
    }
};

class Trapezoid : public Shape {
    double upperBase, lowerBase, height;
public:
    Trapezoid(double u, double l, double h) : upperBase(u), lowerBase(l), height(h) {}
    double getArea() const override {
        return (upperBase + lowerBase) * height * 0.5;
    }
};

class Triangle : public Shape {
    double base, height;
public:
    Triangle(double b, double h) : base(b), height(h) {}
    double getArea() const override {
        return base * height * 0.5;
    }
};

int main() {
    double r, s, rw, rh, tu, tl, th, tb, tht;
    cin >> r >> s >> rw >> rh >> tu >> tl >> th >> tb >> tht;

    Circle circle(r);
    Square square(s);
    Rectangle rect(rw, rh);
    Trapezoid trap(tu, tl, th);
    Triangle tri(tb, tht);

    const Shape* shapes[] = { &circle, &square, &rect, &trap, &tri };
    double total = 0.0;
    for (const auto* shape : shapes) {
        total += shape->getArea();
    }

    cout << fixed << setprecision(3);
    cout << "total of all areas = " << total << endl;

    return 0;
}

Tags: C++ Polymorphism abstract base class shape area virtual function

Posted on Sun, 30 Aug 2026 16:49:57 +0000 by phpnewbie25