Late binding in C++: which feature enables runtime selection of the method implementation?
-
AVirtual function
-
BOperator function
-
CConst function
-
DStatic function
Answer
Correct Answer: Virtual function
Explanation
Introduction / Context:Late binding (dynamic binding) means the function to call is determined at runtime based on the object’s dynamic type. In C++, this is the cornerstone of runtime polymorphism and is essential for designing flexible interfaces that derived classes can override.
Given Data / Assumptions:
- We consider class hierarchies with base pointers/references.
- We differentiate between compile-time and runtime dispatch.
- We focus on the mechanisms built into C++.
Concept / Approach:
A virtual function in a base class allows derived classes to provide their own implementations. When you invoke the function through a base reference or pointer, the call is dispatched via the vtable to the most-derived override at runtime. Non-virtual member functions bind at compile time. “Operator function” is just a function implementing an operator overload and usually binds statically; “const function” only constrains mutation of the object; “static function” has no this and cannot be virtual, so it does not participate in dynamic binding.
Step-by-Step Solution:
1) Mark a base member as virtual. 2) Override it in derived classes with the same signature. 3) Call through a base pointer/reference. 4) Observe runtime selection of the derived override.Verification / Alternative check:
Removing the virtual keyword changes dispatch to static, making the base implementation run even when the dynamic type is derived (for non-overridden names, hiding rules aside).
Why Other Options Are Wrong:
Operator function: operator overloading is resolved at compile time.
Const function: affects mutability, not dispatch.
Static function: no virtual mechanism; it cannot be overridden polymorphically.
Common Pitfalls:
- Expecting late binding without virtual.
- Confusing templates (static polymorphism) with virtual functions (dynamic polymorphism).
Final Answer:
Virtual function