Abstract Shapes
Completed
Write an abstract class Shape with pure virtual area() and name(). Implement Circle, Rect and Triangle. Read shapes into a vector<unique_ptr<Shape>>, print each name area (2 decimals) and the total.
Input
n, then lines circle r, rect w h, triangle b h.
Output
n + 1 lines.
Example
Input
3 circle 1 rect 2 3 triangle 4 5
Output
circle 3.14 rect 6.00 triangle 10.00 total 19.14
Editor
C++
Hints
= 0 makes a function pure virtual; the class becomes abstract.
Solution explanation
The loop works with any shape through the base-class interface.
Show solution
#include <iostream>
#include <iomanip>
#include <memory>
#include <string>
#include <vector>
#include <cmath>
using namespace std;
class Shape {
public:
virtual ~Shape() = default;
virtual double area() const = 0;
virtual string name() const = 0;
};
class Circle : public Shape {
public:
explicit Circle(double r) : r_(r) {}
double area() const override { return M_PI * r_ * r_; }
string name() const override { return "circle"; }
private:
double r_;
};
class Rect : public Shape {
public:
Rect(double w, double h) : w_(w), h_(h) {}
double area() const override { return w_ * h_; }
string name() const override { return "rect"; }
private:
double w_, h_;
};
class Triangle : public Shape {
public:
Triangle(double b, double h) : b_(b), h_(h) {}
double area() const override { return b_ * h_ / 2; }
string name() const override { return "triangle"; }
private:
double b_, h_;
};
int main() {
int n;
cin >> n;
vector<unique_ptr<Shape>> shapes;
for (int i = 0; i < n; i++) {
string kind;
cin >> kind;
if (kind == "circle") {
double r; cin >> r;
shapes.push_back(make_unique<Circle>(r));
} else if (kind == "rect") {
double w, h; cin >> w >> h;
shapes.push_back(make_unique<Rect>(w, h));
} else {
double b, h; cin >> b >> h;
shapes.push_back(make_unique<Triangle>(b, h));
}
}
double total = 0;
cout << fixed << setprecision(2);
for (const auto &s : shapes) {
cout << s->name() << " " << s->area() << "\n";
total += s->area();
}
cout << "total " << total << "\n";
return 0;
}