Our problem from inheritance is that we can’t access members of a derived object if the pointer pointing to it is of a base type.
The solution is a virtual function, via the virtual
keyword. If a function is declared as a virtual function in the base class, and re-defined or overwritten in the derived class, then a call to that function via a base class pointer will invoke the function depending on the type of the object.
Non-virtual functions are invoked depending on the type of pointer, known at compile-time. Virtual functions are invoked depending on the type the pointer points to, known ad run-time.
A class that inherits a virtual function is called a polymorphic class.
Extensions
Objects of the base class may sometimes never be intended to be instantiated and only serve to derive other classes. We can enforce pure virtual methods that don’t have a definition by default, so any derived class should re-define.
A class with one or more pure virtual functions is called an abstract class, because objects of these classes cannot be instantiated. They’re also sometimes called interfaces, because they force derived classes to define the virtual function they inherit.