3

Possible Duplicate:
object size with virtual

Does virtual inheritance change the size of the derived class? I executed the following code, where I have two derived classes one virtually inherited and the other non virtually inherited:

class A {
 public:
int a;
  virtual void a1();
};


class non_vir_der: public A{
 public:
int c;
  virtual void aa();
};


class vir_der: public virtual A{
public:
int d;
virtual void bb();
};

int main()
{
cout<<sizeof(non_vir_der)<<"\n";
cout<<sizeof(vir_der)<<"\n";
return 0;
}

output:

12 (imo: 4(int a)+ 4(int c)+ 4(vir ptr))

16 (extra 4?)

to check again if i had missed something, i tried the minimum code required, by deleting all ints in the classes and the output was:

4

4

the second output indicates that the two derived classes are of same size. Why is the size of vir_der 16 in the first run, why is it not 12?

Community
  • 1
  • 1

2 Answers2

6

This behavior is completely implementation-specific and there are no guarantees about what will happen. That said, most compilers implement virtual inheritance by having a single copy of the base class lying around, then having each instance of the derived class store a pointer inside its class body that points to that one unique instance. That way, if you cast the object to its virtual base, the compiler can emit code to find out where that object is. On a 32-bit system, this means that virtual inheritance might increase the size of the object by four bytes, as you've observed.

So why is there no difference if there are no data members? I'm not sure, but I'm guessing that this is because the compiler is smart enough to realize that if you have a virtual base class with no data members, you don't ever actually need to access anything contained within it. Consequently, the object can be optimized by eliminating the extra pointer to the virtual base, since there's never a way that it could be accessed. I could be wrong about this, though.

Hope this helps!

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
0

Basically,when you declare a function or class virtual,the compiler instantiates a virtual

pointer which is required in case of UPCASTING .Actually,a virtual pointer table is created

where all virtual instances are stored with their actual address .Thus,when you inherited

virtual class in 2nd case ,an extra *vptr got created.

Now the second case, why is that 4 in both cases...That's completely compiler specific.

It should have been 1 in 1st case and 4 in 2nd case according to simple logic.

Thanx

vijay
  • 2,034
  • 3
  • 19
  • 38