C++ Virtual Function Dispatch: Static and Dynamic Binding Mechanics
Consider the behavior of default arguments combined with virtual function overrides:
class BaseClass {
public:
virtual void DisplayValue(int val = 10);
};
void BaseClass::DisplayValue(int val) {
std::cout << "BaseClass::DisplayValue, val = " << val << std::endl;
}
class DerivedClass : public BaseClass {
public:
void DisplayValue(int val = 20) override;
};
void DerivedClass::DisplayValue(int val) {
std::cout << "DerivedClass::DisplayValue, val = " << val << std::endl;
}
Execution scenarios:
DerivedClass derivedObj;
BaseClass* basePtr = (BaseClass*)&derivedObj;
basePtr->DisplayValue();
(*basePtr).DisplayValue();
derivedObj.DisplayValue();
((BaseClass)derivedObj).DisplayValue();
Compiler implementation details reveal distinct binding mechanisms for these calls:
-
Direct Object Invocation (
derivedObj.DisplayValue()): The compiler resolves the target function address at compile time, resulting in static binding. The call is directly hardcoded toDerivedClass::DisplayValue()with out traversing the vtable. -
Pointer and Dereferenced Pointer Invocation (
basePtr->DisplayValue()and(*basePtr).DisplayValue()): Both invoke dynamic binding. The generated assembly retrieves the vtable pointer from the object's memory, locates the appropriate function slot, and performs an indirect call. The runtime type of the object dictates which implementation executes. -
Object Slicing via Cast (
((BaseClass)derivedObj).DisplayValue()): This cast triggers object slicing. A completely new, temporaryBaseClassinstance is constructed using the base class copy constructor. During the execution of this copy constructor, the vptr of the new object is explicitly set toBaseClass::vftable, overwriting the originalDerivedClassvptr. Consequently, the dynamic dispatch resolves toBaseClass::DisplayValue. Modifying members within this temporary sliced object affects only the temporary copy and leaves the originalderivedObjunaltered.