Lesson 5 of 6
Mini Project Part 4 - Shape Hierarchy with virtual area()
Build a complete shape hierarchy with Circle, Rectangle, Triangle, and Square. Demonstrates: pure virtual base, `override`/`final`, polymorphic `std::vector<std::unique_ptr<Shape>>`, runtime type info with `dynamic_cast`, and an area-based sort using `std::sort` with a lambda comparator.
Shape Hierarchy - Polymorphism & std::unique_ptr Container
#include <iostream>
#include <vector>
#include <memory>
#include <algorithm>
#include <string>
#include <cmath>
#include <iomanip>
class Shape {
public:
virtual ~Shape() = default;
virtual double area() const = 0;
virtual double perimeter() const = 0;
virtual std::string name() const = 0;
virtual void draw() const = 0;
void describe() const {
std::cout << std::fixed << std::setprecision(2);
std::cout << std::setw(12) << name()
<< " area=" << std::setw(8) << area()
<< " perimeter=" << std::setw(8) << perimeter()
<< "
";
}
};
class Circle final : public Shape {
double r_;
static constexpr double PI = 3.14159265358979;
public:
explicit Circle(double r) : r_(r) {}
double area() const override { return PI * r_ * r_; }
double perimeter() const override { return 2 * PI * r_; }
std::string name() const override { return "Circle"; }
void draw() const override { std::cout << "(O) r=" << r_ << "
"; }
double radius() const { return r_; }
};
class Rectangle : public Shape {
protected:
double w_, h_;
public:
Rectangle(double w, double h) : w_(w), h_(h) {}
double area() const override { return w_ * h_; }
double perimeter() const override { return 2*(w_+h_); }
std::string name() const override { return "Rectangle"; }
void draw() const override {
std::cout << "[#] " << w_ << "x" << h_ << "
";
}
};
class Square final : public Rectangle {
public:
explicit Square(double s) : Rectangle(s, s) {}
std::string name() const override { return "Square"; }
};
class Triangle : public Shape {
double a_, b_, c_;
public:
Triangle(double a, double b, double c) : a_(a), b_(b), c_(c) {
if (a+b <= c || a+c <= b || b+c <= a)
throw std::invalid_argument("Invalid triangle sides");
}
double area() const override {
double s = (a_+b_+c_)/2.0; // Heron's formula
return std::sqrt(s*(s-a_)*(s-b_)*(s-c_));
}
double perimeter() const override { return a_+b_+c_; }
std::string name() const override { return "Triangle"; }
void draw() const override {
std::cout << "/\ sides=" << a_ << "," << b_ << "," << c_ << "
";
}
};
int main() {
// Polymorphic container - unique_ptr for ownership
std::vector<std::unique_ptr<Shape>> shapes;
shapes.push_back(std::make_unique<Circle>(5.0));
shapes.push_back(std::make_unique<Rectangle>(4.0, 6.0));
shapes.push_back(std::make_unique<Square>(3.0));
shapes.push_back(std::make_unique<Triangle>(3.0, 4.0, 5.0));
shapes.push_back(std::make_unique<Circle>(2.5));
std::cout << "=== All Shapes ===
";
for (const auto& s : shapes) s->describe();
// Sort by area (smallest first) - lambda with virtual area() call
std::sort(shapes.begin(), shapes.end(),
[](const auto& a, const auto& b) {
return a->area() < b->area();
});
std::cout << "
=== Sorted by Area ===
";
for (const auto& s : shapes) s->describe();
// Total area
double total = 0;
for (const auto& s : shapes) total += s->area();
std::cout << "
Total area: " << std::fixed << std::setprecision(2) << total << "
";
// dynamic_cast - safe downcasting
for (const auto& s : shapes) {
if (const Circle* c = dynamic_cast<const Circle*>(s.get())) {
std::cout << "Found circle with radius " << c->radius() << "
";
}
}
return 0;
}Common Mistakes
- `dynamic_cast` on a non-pointer returns null, not crash - `dynamic_cast<Circle*>(ptr)` returns `nullptr` if ptr doesn't actually point to a Circle. Always null-check the result. For references, `dynamic_cast<Circle&>(ref)` throws `std::bad_cast` on failure.
- Storing derived objects by value in a `vector<Shape>` - `vector<Shape>` object slices every derived object to just the Shape part. Always store by pointer (preferably `unique_ptr<Shape>`) for polymorphic containers.
- Not sorting with a stable algorithm when relative order matters - `std::sort` is not stable (elements with equal area may reorder). Use `std::stable_sort` if you need to preserve insertion order among equal-area shapes.
Tip
Tip
Practice Mini Project Part 4 Shape Hierarchy with virtual area in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Vector of Smart Pointers (std::vector<std::unique_ptr<Shape>>) executing virtual area() & draw()
Practice Task
Note
Practice Task - (1) Write a working example of Mini Project Part 4 Shape Hierarchy with virtual area from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Mini Project Part 4 Shape Hierarchy with virtual area is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready cpp code.
Key Takeaways
- Build a complete shape hierarchy with Circle, Rectangle, Triangle, and Square.
- `dynamic_cast` on a non-pointer returns null, not crash - `dynamic_cast<Circle*>(ptr)` returns `nullptr` if ptr doesn't actually point to a Circle. Always null-check the result. For references, `dynamic_cast<Circle&>(ref)` throws `std::bad_cast` on failure.
- Storing derived objects by value in a `vector<Shape>` - `vector<Shape>` object slices every derived object to just the Shape part. Always store by pointer (preferably `unique_ptr<Shape>`) for polymorphic containers.
- Not sorting with a stable algorithm when relative order matters - `std::sort` is not stable (elements with equal area may reorder). Use `std::stable_sort` if you need to preserve insertion order among equal-area shapes.
Finished this lesson?