Reputation: 33
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 ?
Upvotes: 1
Views: 335
Reputation:
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.
Upvotes: 2
Reputation: 182753
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.
Upvotes: 5
Reputation: 206508
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.
Upvotes: 6