Define polymorphic classes
suggest changeA 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?
- The
virtualkeyword enables runtime polymorphism. A call through a base-class pointer or reference invokes the final overrider for the object's dynamic type. - The
= 0makesget_surface()a pure virtual function.Shapetherefore does not need to provide a general surface-area calculation. - A base class intended for polymorphic deletion needs a public virtual destructor. Here
~Shape()is defaulted because it has no custom cleanup to perform. - A class may also define non-virtual member functions.
get_doubled_surface()is non-virtual, but its call to the virtualget_surface()still dispatches dynamically. - A class that contains at least one pure virtual function is an abstract class. Abstract classes cannot be instantiated. You can use pointers or references to an abstract class, and other classes can derive from it.
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:
- A function that is virtual in the base class remains virtual in derived classes, so repeating
virtualis unnecessary. Addoverrideto let the compiler detect accidental signature mismatches, including differences inconstqualification. - A derived class remains abstract unless it provides final overriders for all inherited pure virtual functions.
- A derived class need not override non-pure virtual functions when the inherited behavior is suitable.
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*.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents