⚡0 XP🔥0

Polymorphism and Virtual Functions

Lesson 8 of 12 ⏱ 6 min read ✎ 1 exercises ❓ 4-question quiz ▶ Runs C++

Run-time polymorphism with virtual functions, override, base-class pointers, pure virtual functions and abstract classes, virtual destructors and how the vtable works.

Polymorphism means "many forms": the same call behaves differently depending on the object. C++ has two kinds:

Kind When decided How
Compile-time (static) by the compiler function overloading, operator overloading, templates
Run-time (dynamic) while the program runs virtual functions called through base pointers/references

The problem without virtual#

▶ Try it YourselfC++
Ctrl + Enter to run
Output
Woof
...

Virtual functions#

Mark the base function virtual and the call is decided by the actual object at run time:

▶ Try it YourselfC++
Ctrl + Enter to run
Output
Woof
Meow
Moo

One loop handles every animal - and adding a Lion class later needs no change to the loop. That is the real power of polymorphism: code written against the base class works with types that did not even exist when it was written.

हिंदी में समझें

virtual लगाने पर C++ program चलते समय (run time) देखता है कि pointer असल में किस object की ओर इशारा कर रहा है, और उसी का function चलाता है। इसलिए एक ही loop a->speak() से Dog "Woof", Cat "Meow" बोलती है। नई class जोड़ने पर पुराना code बदलना नहीं पड़ता।

Tip

Write override on every overriding function. If you make a typo in the name or parameters, the compiler gives an error instead of silently creating a new, unrelated function.

Pure virtual functions and abstract classes#

Sometimes the base class cannot sensibly implement a function - what is the area of a generic "Shape"? Make it pure virtual with = 0. A class with at least one pure virtual function is abstract: you cannot create objects of it, only of derived classes that implement the function.

▶ Try it YourselfC++
Ctrl + Enter to run
Output
UPI: paying 2500 + fee 0
Card: paying 2500 + fee 50
NetBanking: paying 2500 + fee 10

unique_ptr (from <memory>) owns a heap object and deletes it automatically - no manual delete.

Virtual destructors#

If you delete a derived object through a base pointer, the base class must have a virtual destructor, otherwise only the base part is destroyed:

▶ Try it YourselfC++
Ctrl + Enter to run
Output
~Derived (buffer freed)
~Base

Remove virtual from ~Base and run again: ~Derived is skipped and the buffer leaks.

How it works: the vtable#

For each class with virtual functions, the compiler builds a virtual table (vtable) - an array of pointers to that class's versions of the virtual functions. Every object gets a hidden pointer (vptr) to its class's vtable. A virtual call does obj->vptr->table[slot](), one extra indirection, which is why virtual calls are very slightly slower than normal calls - a cost almost always worth paying.

dynamic_cast#

To check what a base pointer really points to, use dynamic_cast (works only with polymorphic classes). It returns nullptr if the cast is not possible:

▶ Try it YourselfC++
Ctrl + Enter to run
Output
Circle with r = 2
Not a circle
Circle with r = 2
Note

Needing many dynamic_cast checks is usually a sign that the behaviour should be a virtual function instead.

Summary#

  • virtual + base pointer/reference = run-time polymorphism; mark overrides with override.
  • = 0 makes a pure virtual function; a class with one is abstract (an interface).
  • Give polymorphic base classes a virtual destructor; prefer unique_ptr to manual delete.
  • Virtual calls go through the vtable; dynamic_cast checks the real type.

Practice Exercises

Write your code, then press Check. Your program is tested automatically.

1

Shapes with an abstract class

Make Shape abstract with virtual double area() const = 0; and virtual string name() const = 0;. Implement Circle(r), Rectangle(l, b) and Triangle(base, height). The given main prints each shape and the total:

Circle: 28.27
Rectangle: 24.00
Triangle: 15.00
Total area: 67.27
Expected output:
Circle: 28.27
Rectangle: 24.00
Triangle: 15.00
Total area: 67.27

Quick Quiz

Q1.

What makes a function call resolve at run time based on the actual object?

Q2.

virtual double area() const = 0; declares a...

Q3.

Why should a base class with virtual functions have a virtual destructor?

Q4.

Function overloading is ___ polymorphism; virtual functions give ___ polymorphism.