c++ - Why does virtual keyword increase the size of derived a class? -


i have 2 classes - 1 base class , 1 derived :

class base {   int ;    public :   virtual ~ base () { } };  class derived :  virtual public base { int j ; };  main()  { cout << sizeof ( derived ) ; } 

here answer 16. if instead non-virtual public inheritance or make base class non-polymorphic , answer 12, i.e. if :

class base {   int ;   public : virtual ~ base () { } };  class derived :  public base { int j ; };  main()  { cout << sizeof ( derived ) ; } 

or

class base {  int ;  public : ~ base () { } };  class derived :  virtual public base { int j ; };  main()  { cout << sizeof ( derived ) ; } 

in both cases answer 12.

can please explain why there difference in size of derived class in 1st , other 2 cases ?

( work on code::blocks 10.05, if need )

the point of virtual inheritance allow sharing of base classes. here's problem:

struct base { int member; virtual void method() {} }; struct derived0 : base { int d0; }; struct derived1 : base { int d1; }; struct join : derived0, derived1 {}; join j; j.method(); j.member; (base *)j; dynamic_cast<base *>(j); 

the last 4 lines ambiguous. have explicitly whether want base inside derived0, or base inside derived1.

if change second , third line follows, problem goes away:

struct derived0 : virtual base { int d0; }; struct derived1 : virtual base { int d1; }; 

your j object has 1 copy of base, not two, last 4 lines stop being ambiguous.

but think how has implemented. normally, in derived0, d0 comes right after m, , in derived1, d1 comes right after m. virtual inheritance, both share same m, can't have both d0 , d1 come right after it. you're going need form of indirection. that's pointer comes from.

if want know layout is, depends on target platform , compiler. "gcc" isn't enough. many modern non-windows targets, answer defined itanium c++ abi, documented @ http://mentorembedded.github.com/cxx-abi/abi.html#vtable.


Comments

Popular posts from this blog

jquery - Invalid Assignment Left-Hand Side -

java - Play! framework 2.0: How to display multiple image? -

gmail - Is there any documentation for read-only access to the Google Contacts API? -