views:

824

answers:

2

Hi,

I was recently asked in an interview about object layout with virtual functions and multiple inheritance involved.
I explained it in context of how it is implemented without multiple inheritance involved (i.e. how the compiler generated the virtual table, insert a secret pointer to the virtual table in each object and so on).
It seemed to me that there was something missing in my explanation.
So here are questions (see example below)

  1. What is the exact memory layout of the object of class C.
  2. Virtual tables entries for class C.
  3. Sizes (as returned by sizeof) of object of classes A, B and C. (8, 8, 16 ?? )
  4. What if virtual inheritance is used. Surely the sizes and virtual table entries should be affected ?

Example code:

class A {  
  public:   
    virtual int funA();     
  private:  
    int a;  
};

class B {  
  public:  
    virtual int funB();  
  private:  
    int b;  
};  

class C : public A, public B {  
  private:  
    int c;  
};

Thanks!

+5  A: 
Tobias
Well explained. Thanks."The reason why sizeof(C) == 20 and not 16 is that gcc gives it 8 bytes for the A subobject, 8 bytes for the B subobject and 4 bytes for its member int c."What about virtual table pointer within object of C?
Ankur
The compiler can "recycle" the A-subobject's vtable pointer save 4 bytes per instance this way.
Tobias
+3  A: 

1 thing to expect with multiple inheritance is that your pointer can change when casting to a (typically not first) subclass. Something you should be aware of while debugging and answering interview questions.

stefaanv
I think the article at the following link elaborates your point. Right?http://www.phpcompiler.org/articles/virtualinheritance.html
Ankur
Yes, it is the part that shows upcasting.
stefaanv