C++ - Polymorphism & Virtual Functions

Overview

Estimated time: 40–60 minutes

Use virtual functions for runtime polymorphism. Override in derived classes and prevent further overrides with final.

Learning Objectives

  • Declare virtual functions and override correctly.
  • Understand object slicing and use references/pointers for polymorphism.

Example

struct Base{ virtual ~Base()=default; virtual void speak() const { std::cout << "base\n"; } };
struct Dog: Base{ void speak() const override { std::cout << "woof\n"; } };
void say(const Base& b){ b.speak(); }

Common Pitfalls

  • Calling virtual functions in constructors/destructors calls the base implementation.