C++ abstract classes and virtual dispatch
Invoke derived behavior through a base reference.
On this page
Classes, inheritance, and references.
- Invoke derived behavior through a base reference.
- Predict the sample output and explain the state changes.
- Complete the practice task and check the boundary cases.
The concept
A pure virtual method defines a required operation and makes the base class abstract. A derived class supplies the implementation with override.
A base reference preserves the dynamic type of the object. Virtual dispatch calls Rectangle::area. A virtual destructor supports correct destruction if a derived object is later owned through a base pointer.
Code example
#include <iostream>
class Shape {
public:
virtual int area() const = 0;
virtual ~Shape() = default;
};
class Rectangle : public Shape {
int width_, height_;
public:
Rectangle(int w, int h) : width_(w), height_(h) {}
int area() const override { return width_ * height_; }
};
int main() {
Rectangle rectangle(3, 4);
const Shape& shape = rectangle;
std::cout << shape.area() << '\n';
}12
Follow the code
Open the walkthrough to inspect the example one step at a time.
Show guided walkthrough
#include <iostream>class Shape {public: virtual int area() const = 0; virtual ~Shape() = default;};class Rectangle : public Shape { int width_, height_;public: Rectangle(int w, int h) : width_(w), height_(h) {} int area() const override { return width_ * height_; }};int main() { Rectangle rectangle(3, 4); const Shape& shape = rectangle; std::cout << shape.area() << '\n';}Follow the example
Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.
View the complete dry-run table
| Step / line | What happens | State after step | Output so far |
|---|---|---|---|
| Construct the concrete shape. | width_ = 3, height_ = 4 | — | |
| Bind a base reference to the same object. | dynamic type = Rectangle | — | |
| Dispatch to the derived override. | return = 12 | — | |
| Print the result. | return = 12 | 12 |
Behind the scenes
How C++ processes this code
The C++ compiler produces a native executable. Execution enters main, where objects and function calls perform the work.
Cost and common mistakes
O(1) arithmetic work and fixed object storage.
- Copying derived objects into non-abstract base values can slice derived state.
- This sample assumes small nonnegative dimensions; it does not validate dimensions or multiplication overflow.
Try it yourself
Implement a Square derived from Shape.
Reveal answer and reasoning
Store one side and override area to return side * side. A side of 5 gives 25 through a Shape reference.