In terms of OOP, Binding is the concept of how a call to a function is made to the function body.
All variables and functions have an address, and binding is the process used to convert their identifiers into an address.
There are two main types of binding:
- Early / Static / Compile-Time Binding / Static Dispatch
- Used when the compiler can associate the identifier with an address
- Only option in C
- Late / Dynamic / Run-Time Binding / Dynamic Dispatch
- Used when the compiler doesn't know or have information to associate the identifier with an address
- Implemented using virtual functions (with an object address of the Base class type)
- akin to an 'abstract', placeholder
We are interested in late binding since it is this ability that allows our code to become polymorphic.
Late binding is implemented by the compiler when the keyword virtual is applied to a class's function. This informs the compiler not to implement early binding and instead implement the late binding mechanisms. It achieves this by creating a (hidden) VTABLE for each class that contains a virtual function, in which the addresses of the virtual functions are stored for that class. It then creates a (hidden) pointer VPTR for each class that points to the VTABLE for the object. When a virtual function call is made via a base class type, the compiler creates code to get the VPTR to lookup the correct (derived) function address in the VTABLE.