Skip to content
Tutorials Center
My learning

Topics

Lesson 79 of 171 ยท Object-Oriented Programming

Virtual Functions and Polymorphism

Learn C++ virtual functions - dynamic dispatch, override and final, how vtables work, why base classes need virtual destructors, and how object slicing happens.

Inheritance lets a Circle be used wherever a Shape is expected. But when code holds a Shape& and calls draw(), which function runs: Shape::draw or Circle::draw? Without help from you, C++ picks Shape::draw, because that's the type the code can see. Mark the function virtual, and C++ instead looks at the actual object at run time and calls Circle::draw. That one keyword is the core of runtime polymorphism: writing code against a base class that automatically does the right thing for every derived class, including ones written years later.

This lesson explains static versus dynamic binding, virtual, override and final, how compilers implement virtual calls with vtables, why any base class you delete through must have a virtual destructor, and the two classic traps: object slicing and virtual calls inside constructors. It builds on Inheritance and Access in Inheritance, Multiple and Virtual Inheritance.

The problem: calls follow the static type

Every expression in C++ has a static type, the type the compiler sees in the source code. A Shape& parameter has static type Shape, even when it refers to a Circle. The object it refers to has a dynamic type, the type it was actually created as. For ordinary (non-virtual) member functions, the compiler decides which function to call from the static type alone. This is called static binding.

C++ Without virtual the base version runs

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Circle::describe only hides Shape::describe; it doesn't replace it. Code that sees the object as a Shape never finds out it's a circle. That's exactly what we want to change.

virtual: dispatch on the real object

Declaring a member function virtual in the base class switches it to dynamic binding: when you call it through a reference or pointer, the program checks the object's dynamic type at run time and calls that class's version. A derived class function with the same name and parameters overrides the virtual one. Mark it with override so the compiler verifies that it really does.

C++ virtual and override

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

introduce was written once, against Shape, and it works for every shape. Adding a Triangle tomorrow needs no change to introduce or to the loop. That's the payoff of polymorphism: code that uses an abstraction is closed to modification but open to extension.

A few rules about virtual functions:

  • Dispatch needs a reference or a pointer. Calling c.describe() on an object by name always uses its own class; there's nothing to look up.
  • virtual is inherited. Once a function is virtual in a base, it's virtual in every derived class, with or without the keyword. Don't repeat virtual in derived classes; write override instead.
  • The signature must match exactly: same name, same parameter types, same const and reference qualifiers. The return type must be the same, or a pointer/reference to a more derived class (a covariant return type).
  • A derived class may skip overriding. Dot doesn't override anything, so the base versions run.
  • Inside an override you can call the base version with a qualified name, such as Shape::describe();. Qualification turns off virtual dispatch for that call.
  • Static member functions, constructors and templates of member functions can't be virtual.

override catches silent mistakes

Before C++11 there was no override, and a tiny signature difference silently created a new, unrelated function instead of an override. The code compiled, and the base version kept running. override turns that bug into a compile error.

C++ A missing const breaks overriding

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The program prints [base] hello, not [file] hello. This time GCC also noticed: our server compiles with -Wall, which since GCC 13 includes -Woverloaded-virtual, so the output starts with a warning that Logger::write "was hidden" by FileLogger::write. That warning only fires in some situations (for example, not when the base has another overload that is overridden), and many projects don't enable it. override is the reliable tool: add it (and fix the const) and the bug can't compile. Use it on every override.

final

final is the opposite tool. On a virtual function it means "no class below this one may override it". On a class it means "nobody may inherit from this class at all":

C++
class Circle : public Shape {
public:
    void describe() const final;         // derived classes of Circle can't override describe
};

class Token final {                      // class Special : public Token is a compile error
    // ...
};

Besides documenting intent, final helps performance: when the compiler knows a function can't be overridden further, it can call it directly instead of through the vtable (this is called devirtualization).

How virtual calls work: vtables

The C++ standard doesn't say how virtual functions are implemented, but every mainstream compiler uses the same scheme:

  1. For each class with virtual functions, the compiler builds one virtual table (vtable): an array of pointers to that class's version of each virtual function.
  2. Each object of such a class gets a hidden member, the vptr, that points to its class's vtable. Constructors set it.
  3. A virtual call shape.area() becomes: read the object's vptr, look up the area slot in the table, and call the function stored there.
TEXT
 Circle object          Circle's vtable              Square object          Square's vtable
+-----------+         +--------------------+       +-----------+         +--------------------+
| vptr  ----+-------> | ~Circle            |       | vptr  ----+-------> | ~Square            |
| radius_   |         | Circle::describe   |       | side_     |         | Square::describe   |
+-----------+         | Circle::area       |       +-----------+         | Square::area       |
                      +--------------------+                             +--------------------+

So the cost of virtual is small but real: one extra pointer per object, and an indirect call that the compiler usually can't inline. You can see the hidden pointer in sizeof:

C++ The hidden vptr in sizeof

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

On our 64-bit server, Plain is 4 bytes and both other types are 16: an 8-byte vptr plus the int, padded to 8-byte alignment (see Memory Layout). The number of virtual functions doesn't change the object size; it only makes the shared table longer.

In practice the indirect call costs a few nanoseconds at most. It matters in tight inner loops over millions of small objects, not in ordinary application code. If you need polymorphism with zero runtime cost, templates provide static polymorphism (see Function Templates).

Virtual destructors are mandatory

Here's the rule that prevents real bugs: if a class is meant to be used polymorphically, give it a public virtual destructor. When you delete an object through a base pointer (which is exactly what std::unique_ptr<Base> does), the destructor call is dispatched like any other member function. With a non-virtual destructor, only ~Base runs, the derived part is never destroyed, and the behavior is undefined.

C++
class Base {
public:
    ~Base() { }                          // NOT virtual
    virtual void run() { }
};

class Derived : public Base {
    std::vector<int> data_ = std::vector<int>(1000);
};

Base* p = new Derived;
delete p;     // undefined behavior: ~Derived never runs, data_ leaks
// GCC: warning: deleting object of polymorphic class type 'Base' which has
//      non-virtual destructor might cause undefined behavior [-Wdelete-non-virtual-dtor]

With virtual ~Base() = default; the delete goes through the vtable, ~Derived runs first (destroying its members), then ~Base:

C++ A virtual destructor runs the whole chain

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

(The = 0 makes send a pure virtual function; the next lesson, Abstract Classes and Interfaces, is about exactly that.)

The usual guideline: a base class destructor should be either public and virtual (the class is meant to be deleted through base pointers) or protected and non-virtual (deleting through the base is forbidden, so no virtual call is needed). virtual ~Base() = default; is the one-line default for any polymorphic base.

Object slicing

Polymorphism only works through references and pointers. If you copy a derived object into a base object, by value, only the base part is copied. The derived members are "sliced off", and the copy really is a plain Base, with Base's vptr. No virtual call will ever reach the derived code again.

C++ Slicing by value

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The name survives (it lives in the Animal part), but the dog has forgotten how to bark. Slicing is never a compile error, which makes it dangerous. Prevent it by:

  • taking polymorphic parameters as const Base& or Base&, never Base,
  • storing polymorphic objects as std::vector<std::unique_ptr<Base>> (see Smart Pointers: std::unique_ptr),
  • deleting the copy operations of polymorphic bases (Animal(const Animal&) = delete; and the assignment), or making them protected, so accidental copies fail to compile. If you need copies, add a virtual clone() function that returns a std::unique_ptr<Base>.

Virtual calls in constructors and destructors

While a Base constructor runs, the derived part of the object doesn't exist yet: its members haven't been initialized. So C++ treats the object as a Base during that time (the vptr points to Base's vtable), and a virtual call from the constructor runs the Base version. The same happens in reverse in the destructor: by the time ~Base runs, ~Derived has finished and the derived members are gone.

C++ Virtual calls during construction

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The Widget constructor gets Widget even though the object being built is a Button. Once the Button constructor body runs, the object is a Button and the call dispatches to Button::name. At the end of main, ~Button runs first, then ~Widget, and by then the object is back to being a Widget. This is deliberately safe (Java and C# do dispatch to the derived class here, which can read uninitialized fields), but it surprises people who expect an "initialize" hook. If derived classes need to customize setup, pass the information to the base constructor as an argument, or use a factory function that finishes setup after construction. Calling a pure virtual function (one with no body, see the next lesson) from a constructor, even indirectly, is undefined behavior and usually crashes the program.

Default arguments are static

One last subtle trap: default arguments of a virtual function come from the static type, while the function body comes from the dynamic type.

C++
struct Base    { virtual void greet(int times = 1) const; };
struct Derived : Base { void greet(int times = 3) const override; };

const Base& b = Derived{};
b.greet();    // calls Derived::greet, but with times = 1 (Base's default)

Avoid giving overrides different defaults. The cleanest fix is to put defaults only on a non-virtual public function that calls a virtual one.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Base declares void hello() const (not virtual) and Derived declares its own void hello() const. What does calling hello() through a const Base& that refers to a Derived do?

    Non-virtual calls are bound from the static type of the expression, which is Base. Derived::hello merely hides the base function.
  2. 2. In the base, virtual void save(int id) const;. The derived class writes void save(int id) override; (no const). What happens?

    override asks the compiler to check that a base virtual function with the same signature exists. Without const the signatures differ, so the compiler reports an error instead of creating a new function.
  3. 3. std::unique_ptr<Base> p = std::make_unique<Derived>(); Base has virtual functions but a non-virtual public destructor. What happens when p is destroyed?

    The deleter calls delete on a Base*. With a non-virtual destructor, deleting a derived object through a base pointer is undefined behavior, and in practice the derived destructor is skipped.
  4. 4. Dog overrides sound() to return "Woof". What does void f(Animal a) { print(a.sound()); } print when called with a Dog?

    Passing by value copies only the Animal part into a real Animal object. That object's dynamic type is Animal, so Animal::sound runs. Take const Animal& instead.
  5. 5. Widget's constructor calls the virtual function name(), which Button overrides. Which version runs while a Button is being constructed?

    During the Widget constructor the Button part doesn't exist yet, so the object behaves as a Widget and virtual calls go to Widget's versions.

Summary

  • Non-virtual calls use the static type; virtual functions called through references or pointers use the dynamic type of the object.
  • Mark every override with override so signature mistakes become compile errors. Use final to stop further overriding or inheritance.
  • Compilers implement virtual calls with a per-class vtable and a hidden vptr in each object: one pointer of size and an indirect call per virtual call.
  • A polymorphic base needs a public virtual destructor (virtual ~Base() = default;), or a protected non-virtual one. Deleting through a base without it is undefined behavior.
  • Slicing copies only the base part. Pass polymorphic objects by reference, store them in std::unique_ptr<Base>, and consider deleting base copy operations.
  • Virtual calls in constructors and destructors run the class currently being built or destroyed, never a more derived one. Default arguments come from the static type.

Next: Abstract Classes and Interfaces, where base classes declare what derived classes must do without doing it themselves.