Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
738 views
in Technique[技术] by (71.8m points)

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

Look at the following C++ code

class Base1 {  
public:  
    Base1();  
    virtual ~Base1();  
    virtual void speakClearly();  
    virtual Base1 *clone() const;  
protected:  
    float data_Base1;  
};  

class Base2 {  
public:  
    Base2();  
    virtual ~Base2();  
    virtual void mumble();  
    virtual Base2 *clone() const;  
protected:  
    float data_Base2;  
};  

class Derived : public Base1, public Base2 {  
public:  
    Derived();  
    virtual ~Derived();  
    virtual Derived *clone() const;  
protected:  
    float data_Derived;  
}; 

The 《Inside of C++ Object Model 》4.2 says that the virtual table layout of class Base1,Base2 and Derived is like this: enter image description here

enter image description here

My question is :

The virtual table of the Base1 subObject of class Derived contains Base2::mumble.Why?I know Derived class shared this virtual table with Base1,so I think the function of Base2 should not appear here.Could someone tell me why? Thx.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...