Inheritance and Polymorphism
A class inherits with : public Base. A function marked virtual can be overridden, and a call through a base pointer or reference runs the child version. Give a base class a virtual destructor. A pure virtual function (= 0) makes the class abstract.
Example
#include <iostream>
#include <vector>
#include <memory>
using namespace std;
class Shape {
public:
virtual double area() const = 0;
virtual ~Shape() = default;
};
class Square : public Shape {
double s;
public:
Square(double s) : s(s) {}
double area() const override { return s * s; }
};
class Rect : public Shape {
double w, h;
public:
Rect(double w, double h) : w(w), h(h) {}
double area() const override { return w * h; }
};
int main() {
vector<unique_ptr<Shape>> shapes;
shapes.push_back(make_unique<Square>(3));
shapes.push_back(make_unique<Rect>(2, 5));
for (auto& s : shapes) cout << s->area() << endl;
}Result
9 10
Exercise
Allow a function to be overridden.
double area() const;Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.