Multiple Inheritance Flashcards
Describe the steps in the dispatch algorithm
given an invocation p->f()
- upcast p to B(the uppermost class that defines f) : p’ = static_cast(p);
- find the adress of f in B’s vtable (contains f in the most derived class or a thunk)
- adjust this, downcast p’ to the most drived class that overrides f. (done by thunk)
- invoke f.
In the dispatch algorithm, why do we need to upcast before downcast?
הפוינטר יכול להצביע לכל מיני מקומות באובייקט (כל מיני טיפוסים סטטיים), אנחנו רוצים להגיע לנק’ “אחידה” שממנה יהיה אפשר לעבוד בצורה נוחה.
הנק’ הזו היא המחלקה הראשונה שהגדירה את הפונקציה שמפעילים, בטבלה שלה יהיה המימוש המתאים לטיפוס הדינאמי.
In addition, The thunk has a hard-coded adjustment so we always need to move this to the same location.
How does c++ deal with covariant return?
The compiler adds an entry in the vtable for each possible “parent” type, and then calls f directly or uses a thunk to upcast to the right static type, depending on the receiver.
example:
D inherits from B and E inherits from D. (B
What is diamond inheritance?
same base class occurs in more than one ancestor
What is virtual inheritance?
there is only one sub-object of type base instead of several.
How is the memory layout looks like when there is multiple inheritance and virtual inheritance?
Usually, base classes are at the beginning (by order of initialization), and all virtual bases are at the end.
(Implementation specific, though)
Is it possible to downcast from a virtual base?
No. we do not store back-pointers in virtual bases, a lot of overhead.
We can only use dynamic_cast
What is coincidental ambiguity?
Occurs when two bases happen to define a method with the same signature (actually happens also if just the same name)
(Not caused by diamond inheritance)
How to solve coincidental ambiguity?
- Derived class can disambiguate by overriding
- Caller can disambiguate too
- Can also change one of the bases
What is inherent ambiguity?
Occurs when one base is inherited multiple times
Its methods appear in multiple bases
Can virtual inheritance cause inherent ambiguity?
No. One sub-object, one vtable, one set of fields.
Describe the steps in the Initialization order algorithm for multiple & virtual inheritance
- topo sort on the inheritance order (initialization list order, should be given).
- Apply DFS on the inheritance graph, left-to-right.
- Construct all virtual base classes (immediate and
non-immediate) (if a virtual base depends on non-virtual constructors constuct them first). - constuct non-virtual base classes.