← C++ from Scratch Lesson 43 of 62 · 10 XP

Polymorphism: virtual

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

A pointer or a reference to a base class can point to a derived one. virtual says: "when calling, look at the object's real type":

class Shape {
public:
    virtual ~Shape() = default;               // a virtual destructor — a must for base classes
    virtual double area() const = 0;          // = 0 — "pure virtual": a derived class must implement it
    virtual std::string name() const { return "shape"; }
};

class Circle : public Shape {
public:
    explicit Circle(double r) : r(r) {}
    double area() const override { return 3.14159265 * r * r; }   // override — a check that the method overrides something
    std::string name() const override { return "circle"; }
private:
    double r;
};

std::vector<std::unique_ptr<Shape>> shapes;
shapes.push_back(std::make_unique<Circle>(2));
for (auto &s : shapes) std::cout << s->name() << ' ' << s->area() << '\n';   // Circle::area gets called

Under the hood, an object with virtual methods has a hidden pointer to its class's virtual function table (vtable) — the call goes through it.

Task. Shape with area() and name(); the derived classes Circle(r), Rect(w, h), Square(a) (derived from Rect). Read n shapes (circle r, rect w h, square a), put them into a std::vector<std::unique_ptr<Shape>> and for each one print name area with two decimal places; at the end, total <sum>.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.