Dynamic Binding Implementation Flashcards
What are the steps of virtual function invocation in c++? in the following example: void foo(A* x) { x->f2(); }
- Read vptr at the head of the object,
≈
*reinterpret_cast(x) - Read entry of f2
Index known at compile time! - Call address read on step 2
What happens to the vpointer and vtable in a down-cast?
Nothing. the vptr and vtable don’t change, the only difference is that now the compiler “knows” about additional vtable entries.
Does each (Polymorphic) object has its own vtable?
No. objects of the same type share a vtable, but every object has a vptr.
Where is the vptr located in Borland style?
Virtual pointer is always located at the beginning of the object.
Easy access to vptr – always at the same offset (0).
Where is the vptr located in GNU style?
VPTR is located at the beginning of the first sub-object that has virtual functions
Must add sizeof(Base) to reach vptr – on every virtual function call.
calculation is done at compile-time but the addition at run-time.
When borland style is more efficiant? and when gnu?
borland - virtual function invocations
gnu - casting (no need to adjust pointer)
How is binding in constructors handled in c++?
constructor of base calls a virtual function overriden in derived
The binding of function calls within constructors
must be as if it is static.
What are the steps in constructing B, assuming B inherits from A?
- vptr points to A’s vtable
- construct A
- vptr points to B’s vtable
- construct B
Does an abstract class has a vtable?
yes. because when an inheriting class is constructed, the constructor of the abstract class is called and it’s vtable is used.
How is binding within constructors works in Java?
fully dynamic.
In java there is an initialization phase before constructing, so all fields have default values.
How dynamic languages implement dynamic binding?
Using a dispatch table, aka Method dictionary.
How is “as-if static binding” implemented in the constructors code?
בכניסה לבנאי הקומפיילר שותל קוד שמחליף את ה- vptr להצביע ל- vtbl של הטיפוס הסטטי. הקישור של כל
המתודות הוירטואליות ממשיך לעבור דרך ה- vptr ל- vtbl באינדקס המתאים, אך כיוון שה- vptr מצביע ל-
vtbl של המחלקה הסטטית - אנו מקבלים התנהגות שהיא “כאילו”-סטטית. ביציאה מהבנאי הקומפיילר שותל
קוד שמחליף בחזרה את ה- vptr להצביע למקום אליו הצביע קודם-לכן (ה- vtbl של הטיפוס הדינמי).
What problem can be in binding inside constructors in java?
reference types are initialized to null (default value), therefore if we try to dereference we will get a run-time exception.