C++ virtual table layout of MI(multiple inheritance)

前端 未结 2 1585
遇见更好的自我
遇见更好的自我 2020-12-02 17:22

Look at the following C++ code

class Base1 {  
public:  
    Base1();  
    virtual ~Base1();  
    virtual void speakClearly();  
    virtual Base1 *clone()         


        
相关标签:
2条回答
  • 2020-12-02 17:56

    At runtime when you get:

        Base2 b2;
        Base1* b1_ptr = (Base1*)&b2;
        b1_ptr->mumble();    // will call Base2::mumble(), this is the reason.
    

    Then the Base2::mumble() needs to be invoked! Take care that mumble() is the ONLY virtual method that was overriden in hierarchy. (Even, You may think that clone() is overriden too but that returns different type among classes then it is another signature).

    0 讨论(0)
  • 2020-12-02 18:14

    Well, first of all, I'll remind everyone that the design of the solution to implement polymorphism is an ABI decision outside of the Standard. For example, MSVC and the Itanium ABI (followed by gcc, clang, icc, ...) have different ways to implement this.

    With that out of the way, I think that this is an optimization for lookup.

    Whenever you have a Derived object (or one of its descendant) and lookup the mumble member, you do not need to actually find out the Base2 subobject but can directly act from the Base1 subobject (whose address coincides with Derived subobject, so no arithmetic involved).

    0 讨论(0)
提交回复
热议问题