C/C++ Arena

Step 4 of 8

Polymorphic containers

To store different derived types in one container, store pointers to the base. With std::unique_ptr nothing leaks:

std::vector<std::unique_ptr<Shape>> shapes;
shapes.push_back(std::make_unique<Circle>(1.0));
shapes.push_back(std::make_unique<Rect>(2, 3));
for (const auto& s : shapes) total += s->area();

That's also why the base class needs a virtual destructor: deleting a Circle through a Shape* must run Circle's destructor.

Your turn: write int total_damage(const std::vector<std::unique_ptr<Weapon>>& ws, int hits) that sums damage(hits) across all weapons, and implement Pistol (25 per hit) and Shotgun (80 on the first hit, 20 for each hit after).

Previous: Abstract classes Next: Virtual destructors