0

Referencing the multiple inheritance memory layout, suppose Derived class has a field called int derived_only. If I have a Base1 * b1 and Base2 * b2, both pointing to the same Derived class object, then according to wiki, b1 and b2 have slightly different values due to pointer fixup. My question is, if I call a virtual function, say the virtual clone(), by using either b1 or b2, how does clone() calculate derived_only's address, from either b1 or b2?

Basically, when calling b1->clone() vs b2->clone(), the this pointer passed in is different, then how does clone() know how much offset to add to this to get to derived_only?

QnA
  • 1,035
  • 10
  • 25
  • because it's a virtual function? – apple apple Sep 09 '21 at 14:41
  • if you can get `derived*` from `base*`, I don't think compiler has any hard do that cast itself. – apple apple Sep 09 '21 at 14:42
  • What you have written could be explained with a code snippet, which is much easier to read and make sense than raw explanation – Karen Baghdasaryan Sep 09 '21 at 14:43
  • `b1` points at the `Base1` sub-object of `Derived`. As long as `Base1` isn't a virtual base, it will always be in the same position in `Derived`. The compiler knows where it is, and the call to `clone()` will adjust the pointer as needed. – Pete Becker Sep 09 '21 at 14:44
  • The "how" is inconsequential per the standard. The language only dictates that it works :-) You'll have to track down actual implementations to see what they do. You could, for example, initialize a set of function pointers upon creation of derived class object. Calling through the base class simply uses those same function pointers that have already been set up to call the appropriate function. – AndyG Sep 09 '21 at 15:16

0 Answers0