C++ multiple inheritance and vtables

后端 未结 2 1839
旧时难觅i
旧时难觅i 2021-02-06 10:12

So going back to basics, I\'m trying to wrap my head around vtables and whatnot. In the following example, if I were to, say, pass a B* to some function, how does t

2条回答
  •  情深已故
    2021-02-06 10:37

    With multiple inheritance, the object gets built in parts, each part corresponding to one of the base classes. This includes the vtable pointers. This is necessary because the code interacting with a pointer or reference won't know if it's working with the base class or the derived one, so they must be laid out identically.

    One surprising result is that when you cast a pointer to one of the base classes, its address may change! The compiler generates some code behind the scenes to adjust the pointer to the proper piece of the object.

    C obj;
    A* ap = (A*)&obj;
    B* bp = (B*)&obj;
    bool same = ((void*)ap) == ((void*)bp);  // false!
    

提交回复
热议问题