Virtual Methods
We've learned the advantages of dynamic dispatch in C++ and how it can enable us to execute the methods of a derived class by calling a method on a reference or pointer to a base class.
In this section, we will take an in-depth look at how to tell the compiler to perform dynamic dispatch on a method. The way to specify that we want to use dynamic dispatch for a method is to use the virtual keyword.
The virtual keyword is used in front of a method when declaring it:
class Vehicle { public: virtual void turnOn(); };
We need to remember that the compiler decides how to perform method dispatch based on the static type of the variable that is used when calling the method.
This means that we need to apply the virtual keyword to the type we are using in the code. Let's examine the following exercise to explore the virtual keyword.
Exercise 22: Exploring the Virtual Method
Let's create a program using the concept of inheritance using the virtual keyword:
First, make sure to add the...