C++ abstract classes and virtual dispatch
Invoke derived behavior through a base reference.
C++
#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';
}Output
12
Explanation
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.
Explore the dry run
Guided walkthroughReady
1
#include <iostream>2
class Shape {3
public:4
virtual int area() const = 0;5
virtual ~Shape() = default;6
};7
class Rectangle : public Shape {8
int width_, height_;9
public:10
Rectangle(int w, int h) : width_(w), height_(h) {}11
int area() const override { return width_ * height_; }12
};13
int main() {14
Rectangle rectangle(3, 4);15
const Shape& shape = rectangle;16
std::cout << shape.area() << '\n';17
}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 |
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.