Virtual function (polymorphism)

Applies to: cpp

A virtual function can be overridden by a derived class, and a call through a base-class pointer or reference runs the actual object's version (dynamic dispatch). This is runtime polymorphism: code written against a base interface works for every derived type.

struct Sensor { virtual double read() const = 0; };
struct Lidar : Sensor { double read() const override { return 2.5; } };
void use(const Sensor& s) { s.read(); }  // calls Lidar::read for a Lidar

See also: struct-vs-class, reference