Lesson 16 of 25

Inheritance

Single and Multiple Inheritance

C++ supports single, multiple, and multilevel inheritance. Use public inheritance for is-a relationships.

Example
class Shape {
protected:
    string color;
public:
    Shape(string c) : color(c) {}
    virtual double area() const = 0;  // pure virtual
    virtual ~Shape() = default;
};

class Circle : public Shape {
private:
    double radius;
public:
    Circle(string c, double r) : Shape(c), radius(r) {}

    double area() const override {
        return 3.14159 * radius * radius;
    }
};

class Rectangle : public Shape {
private:
    double width, height;
public:
    Rectangle(string c, double w, double h)
        : Shape(c), width(w), height(h) {}

    double area() const override {
        return width * height;
    }
};

// Polymorphism
Shape* shapes[] = { new Circle("red", 5), new Rectangle("blue", 4, 6) };
for (auto s : shapes) {
    cout << s->area() << endl;
    delete s;
}