Lesson 151 +10 XP

Virtual Functions

Virtual Functions

A virtual function is a base class function that a derived class can override, or replace with its own version. When you call through a base pointer, the derived version runs, not the base one.

Declaring a virtual function

Put the keyword virtual before the function in the base class:

class Shape {
public:
  virtual void draw() { cout << "shape"; }
};

Overriding it in a derived class

The derived class writes the same signature and marks it with override:

class Circle : public Shape {
public:
  void draw() override { cout << "circle"; }
};

Calling through a base pointer

int main() {
  Shape* s = new Circle();
  s->draw();   // prints "circle", not "shape"
  return 0;
}
  • The pointer's declared type is Shape, but the actual object is a Circle.
  • Because draw() is virtual, the call goes to Circle::draw().

The override key

override is optional but strongly recommended. It asks the compiler to verify that a matching virtual exists in the base. If your signature is slightly wrong, the compiler flags it instead of silently creating an unrelated new function.

Why it matters

Virtual dispatch happens at runtime, based on the object's actual type. This is what makes a base pointer to any derived class behave correctly.

TL;DR

  • virtual lets a derived class redefine the base's version.
  • Declare the override, then tag it with override.
  • Calling through a base pointer runs the most derived version.
  • Dispatch happens at runtime based on the real object.
  • override is a safety check for the signature.