Define polymorphic classes

suggest change

A typical example begins with an abstract shape class and derives concrete shapes such as squares and circles from it.

The parent class:

Let’s start with the polymorphic class:

#include <iostream>

class Shape {
public:
    virtual ~Shape() = default;
    virtual double get_surface() const = 0;
    virtual void describe_object() const {
        std::cout << "This is a shape\n";
    }

    double get_doubled_surface() const { return 2 * get_surface(); }
};

How should this definition be read?

Derived classes

Once a polymorphic base class is defined you can derive it. For example:

struct Point {
    double x;
    double y;
};

class Square : public Shape {
    Point top_left_;
    double side_length_;

public: 
    Square(Point top_left, double side_length)
        : top_left_(top_left), side_length_(side_length) {}

    double get_surface() const override {
        return side_length_ * side_length_;
    }

    void describe_object() const override {
        std::cout << "This is a square starting at "
                  << top_left_.x << ", " << top_left_.y
                  << " with a side length of " << side_length_ << '\n';
    }  
};

Some explanations:

Example of instantiation

int main() {
    Square square({10.0, 0.0}, 6.0);
    square.describe_object(); 
    std::cout << "Surface: " << square.get_surface() << '\n';

    Circle circle({0.0, 0.0}, 5.0); // Assume Circle also derives from Shape.

    Shape* shape = &circle;
    shape->describe_object();
    std::cout << "Surface: " << shape->get_surface() << '\n';
}

The final fragment assumes a Circle implementation analogous to Square; it focuses on dispatch through a Shape*.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents