Understanding dynamic binding
Now that we have seen how polymorphism is implemented with virtual functions to allow for dynamic binding of an operation to a specific implementation or method, let’s understand why virtual functions allow for runtime binding.
Non-virtual functions are statically bound at compile time. That is, the address of the function in question is determined at compile time, based on the assumed type of the object at hand. For example, if an object is instantiated of type Student
, a function call would have its prototype verified starting with the Student
class, and if not found, the hierarchy would be traversed upward to each base class, such as Person
, to look for the matching prototype. When found, the correct function call would be patched in. This is how static binding works.
However, a virtual function is a type of function in C++ that employs a dynamic binding at runtime. At compile time, any virtual function call is merely replaced with a lookup...