1
class base
{
};

class der_1:public base
{
};

class der_2:virtual public base
{
};

int main()
{
    der_1 a;  //size of a is 1
    der_2 b;  //size of b is 4  ?? why
    cout<<sizeof(a)<<endl;
    cout<<sizeof(b)<<endl;
    return 0;
}

object b internally contains virtual pointer, so its size is 4 instead of 1(like a). But what this virtual pointer is pointing to ?

3 Answers3

6

This is purely implementation dependent. It depends on how an implementation implements dynamic dispatch/virtualism. And this is the reason C++ standard library provides sizeof to get the actual size so that you don't have to guesstimate/estimate it. Always use it instead of making any assumptions on the size.

However most implementations(read all) use the virtual table and pointer mechanism to achieve this and the additional 4 bytes size you see is for the vptr bookkeeping.

Alok Save
  • 202,538
  • 53
  • 430
  • 533
5

It's probably pointing to the virtual function table for the class. This is necessary, in most implementations, to allow things like dynamic_cast to work.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278
  • but class der_2 donot have any virtual function. so how its virtual table is possible ? – Aditya Sharma Dec 28 '13 at 07:56
  • @AdityaSharma - It has virtual inheritance. That's enough (more than enough!) to trigger the need for a viable. Besides, it's a bad idea to inherit from a base class that does not have a virtual destructor. The compiler emits code assuming that core principles are being followed. There's no reason for a compiler to have special size-reducing handling for classes that inherit virtually from base classes that have no virtual methods. It doesn't make sense. – David Hammen Dec 28 '13 at 08:10
2

The size of pointers will vary between machines. For example on my machine, it is 8.

Size of the classes in case of virtual inheritance

Whenever you have virtual inheritance, the location of the virtual base subobject with respect to the start of the complete type is unknown, so an extra pointer is added to the original object to track where the virtual base is.

Does virtual inheritance increase the size of derived class?

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.

Community
  • 1
  • 1