Calculate areas with polymorphism

Description: Make an abstract class Shape with a pure virtual function area(). Write Circle (radius 2) and Rectangle (3 x 4). Put them in one container and print the total area.

Hint:

  • Use std::vector<std::unique_ptr<Shape>> and a virtual destructor.

Solution

#include <iomanip>
#include <iostream>
#include <memory>
#include <numbers>
#include <vector>

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

class Circle : public Shape {
public:
    explicit Circle(double r) : r(r) {}
    double area() const override { return std::numbers::pi * r * r; }
private:
    double r;
};

class Rectangle : public Shape {
public:
    Rectangle(double w, double h) : w(w), h(h) {}
    double area() const override { return w * h; }
private:
    double w, h;
};

int main() {
    std::vector<std::unique_ptr<Shape>> shapes;
    shapes.push_back(std::make_unique<Circle>(2));
    shapes.push_back(std::make_unique<Rectangle>(3, 4));

    double total = 0;
    for (const auto& s : shapes) total += s->area();
    std::cout << std::fixed << std::setprecision(2) << "Total area: " << total << '\n';
}
Output

Total area: 24.57

How it works

  • The loop uses the base type. C++ calls the area() of the real object (virtual function).
  • The virtual destructor makes sure that the right destructor runs when the smart pointers delete the objects.

Read Polymorphism and Abstract Classes.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.