In C++, how is late binding (deciding the override at runtime) implemented under the hood? Identify the common mechanism used by compilers.
-
AUsing C++ tables
-
BUsing Virtual tables
-
CUsing Indexed virtual tables
-
DUsing polymorphic tables
Answer
Correct Answer: Using Virtual tables
Explanation
Introduction:Virtual functions enable runtime polymorphism: the program chooses which overridden function to run based on the dynamic type of the object. This question asks for the typical implementation device used by mainstream C++ compilers.
Given Data / Assumptions:
- Polymorphic classes declare at least one virtual function.
- We discuss common ABI strategies (Itanium, MSVC) rather than strict standard mandates.
Concept / Approach:Most compilers implement late binding via a vtable (virtual table) per polymorphic type and a vptr inside each object, pointing to the class’s vtable. A virtual call compiles to an indirect call through the vtable entry corresponding to the function’s slot.
Step-by-Step Solution:1) When a class has virtual functions, the compiler emits a vtable listing function pointers.2) Each object stores a hidden vptr initialized by constructors to point at the class’s vtable.3) A call like p->foo() becomes: load vptr, index to foo’s slot, perform indirect call.4) Overrides in derived classes replace entries in the derived class’s vtable.
Verification / Alternative check:Disassembling a polymorphic call shows an indirect jump through a table. ABI docs describe slot layouts and RTTI pointers colocated with the vtable.
Why Other Options Are Wrong:“C++ tables”, “Indexed virtual tables”, “polymorphic tables”: vague or non-standard terms; the accepted term is “virtual table (vtable)”.
Common Pitfalls:Believing the standard mandates vtables—it does not, but they are the de facto implementation. Also, thinking templates require vtables (they do not).
Final Answer:Using Virtual tables