Codiqo

Learn C++ · lesson 45 of 61 · about 11 minutes

Project: The Dragon's Lair

Build an enemy hierarchy, refuse bad enemies with exceptions, and report the lair's threat through one interface.

What you'll learn

  • Design an abstract base class
  • Validate in constructors with exceptions
  • Process objects polymorphically

The dragon's lair

At the top of the stairs is the dragon's lair, and the hero scouts it first. Every enemy is an Enemy, an abstract class with pure virtual threat() and kind(). A band of Goblins is 5 threat each, and a Dragon is 40 plus its age; their constructors throw std::invalid_argument for a count or an age below 1, so a bad enemy is never made. The hero types enemies like goblins 3 until done, and the adventure lists them from most to least threatening and says whether the total is less than the hero's health.

The plan

  • Shape is abstract: pure virtual area() and name()
  • Rectangle and Circle override them, and throw if a size isn't positive
  • main builds shapes from lines like rect 3 4, skips invalid ones, and prints a sorted report

The shape report

#include <algorithm>
#include <iomanip>
#include <iostream>
#include <memory>
#include <stdexcept>
#include <string>
#include <vector>

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

class Rectangle : public Shape {
public:
    Rectangle(double w, double h) : w_(w), h_(h) {
        if (w <= 0 || h <= 0) throw std::invalid_argument("rectangle sides must be positive");
    }
    double area() const override { return w_ * h_; }
    std::string name() const override { return "rectangle"; }

private:
    double w_, h_;
};

class Circle : public Shape {
public:
    explicit Circle(double r) : r_(r) {
        if (r <= 0) throw std::invalid_argument("circle radius must be positive");
    }
    double area() const override { return 3.14159 * r_ * r_; }
    std::string name() const override { return "circle"; }

private:
    double r_;
};

int main() {
    std::vector<std::unique_ptr<Shape>> shapes;
    std::string kind;
    while (std::cin >> kind) {
        try {
            if (kind == "rect") {
                double w, h;
                std::cin >> w >> h;
                shapes.push_back(std::make_unique<Rectangle>(w, h));
            } else if (kind == "circle") {
                double r;
                std::cin >> r;
                shapes.push_back(std::make_unique<Circle>(r));
            }
        } catch (const std::invalid_argument& e) {
            std::cout << "skipped: " << e.what() << "\n";
        }
    }
    std::sort(shapes.begin(), shapes.end(), [](const auto& a, const auto& b) { return a->area() > b->area(); });
    std::cout << std::fixed << std::setprecision(2);
    for (const auto& s : shapes) std::cout << std::left << std::setw(10) << s->name() << s->area() << "\n";
}

Output

skipped: rectangle sides must be positive
circle    12.57
rectangle 12.00
circle    3.14

Tip

Throwing from a constructor means an invalid object is never created at all, so every Shape that exists is guaranteed to be valid.

Keeping ties in order

std::sort is free to swap equal elements around, so two enemies with the same threat could come out in either order. std::stable_sort takes the same arguments and keeps equal elements in the order they were added, which makes the report the same every time.

stable_sort

#include <algorithm>
#include <iostream>
#include <string>
#include <utility>
#include <vector>

int main() {
    std::vector<std::pair<std::string, int>> v = {{"bats", 10}, {"ogre", 30}, {"rats", 10}};
    std::stable_sort(v.begin(), v.end(), [](const auto& a, const auto& b) { return a.second > b.second; });
    for (const auto& [name, threat] : v) std::cout << name << " " << threat << "\n";
}

Output

ogre 30
bats 10
rats 10

Now try it yourself

This lesson is free in Codiqo, with 8 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.