C++ · Course navigation

C++ abstract classes and virtual dispatch

Invoke derived behavior through a base reference.

On this page
Before you start

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

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

Follow the code

Open the walkthrough to inspect the example one step at a time.

Show guided walkthrough
Guided walkthroughReady
1#include <iostream>
2class Shape {
3public:
4 virtual int area() const = 0;
5 virtual ~Shape() = default;
6};
7class Rectangle : public Shape {
8 int width_, height_;
9public:
10 Rectangle(int w, int h) : width_(w), height_(h) {}
11 int area() const override { return width_ * height_; }
12};
13int 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
Prepared trace of the published program. Some rows group repeated iterations.
Step / lineWhat happensState after stepOutput 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.

Further reading