Implementing polymorphism with virtual functions
Polymorphism allows dynamic binding of a method to an operation. Dynamic, or runtime, binding of a method to an operation is important because derived class instances may be pointed to by base class objects (that is, by pointers of a base class type). In these situations, the pointer type does not provide adequate information regarding the correct method that should be applied to the referenced instance. We need another way – one done at runtime – to determine which method applies to each instance.
Often, it is the case that a pointer to an instance of a derived class type will be generalized as a pointer to the base class type. When an operation is applied to the pointer, the correct method for what the object truly is should be applied, rather than the method that seems appropriate for the generalized pointer type.
Let’s begin with the relevant keywords and logistics necessary to define virtual functions...