Chapter 3 – Object-Oriented Programming: Part 5
Let’s introduce the virtual keyword now.
We have a base class with a pure virtual function. It is called pure because it has no implementation (see assignment to 0). If a class have at least one pure virtual function, we cannot create objects of that type – we need a definition for that function.
Now, let’s make a few classes that implement this interface.
We see that we create derived classes (Programmer, Doctor) which override the virtual function, giving their own implementation. We can create objects of type Programmer, or Doctor.
By using a pointer to the base class, we can also assign it to different derived classes and ask them to work. (This is possible because we inherit publicly – is-a relationship – so all Programmers and Doctors are also Workers.
When we have at least one virtual function, each class receives a pointer called vPtr which points to a vTable (virtual table) – that contains the address for each virtual function within that class.