The typical example is an abstract shape class, that can then be derived into squares, circles, and other concrete shapes.
The parent class:
Let’s start with the polymorphic class:
class Shape {
public:
virtual ~Shape() = default;
virtual double get_surface() const = 0;
virtual void describe_object() const { std::cout << "this is a shape" << std::endl; }
double get_doubled_surface() const { return 2 * get_surface(); }
};
How to read this definition ?
virtual
. Here get_surface()
and describe_object()
will obviously be implemented differently for a square than for a circle. When the function is invoked on an object, function corresponding to the real class of the object will be determined at runtime.get_surface()
for an abstract shape. This is why the function is followed by = 0
. This means that the function is pure virtual function.get_double_surface()
is defined in this way.Derived classes
Once a polymorphic base class is defined you can derive it. For example:
class Square : public Shape {
Point top_left;
double side_length;
public:
Square (const Point& top_left, double side)
: top_left(top_left), side_length(side_length) {}
double get_surface() override { return side_length * side_length; }
void describe_object() override {
std::cout << "this is a square starting at " << top_left.x << ", " << top_left.y
<< " with a length of " << side_length << std::endl;
}
};
Some explanations:
virtual
again. But it’s recommended to add the keyword override
at the end of the function declaration, in order to prevent subtle bugs caused by unnoticed variations in the function signature.Example of instantiation
int main() {
Square square(Point(10.0, 0.0), 6); // we know it's a square, the compiler also
square.describe_object();
std::cout << "Surface: " << square.get_surface() << std::endl;
Circle circle(Point(0.0, 0.0), 5);
Shape *ps = nullptr; // we don't know yet the real type of the object
ps = &circle; // it's a circle, but it could as well be a square
ps->describe_object();
std::cout << "Surface: " << ps->get_surface() << std::endl;
}