Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Size of a class in C++ [duplicate]

Tags:

c++

I was testing with the size of base classes and derived classes in C++.

class X {}; 
class Y : public virtual X {}; 
class Z : public virtual X {}; 
class A : public Y, public Z {};

The sizeof each X,Y,Z,A came to 1,8,8,12 respectively. I am not able to understand this. I know the default size of an empty class is 1. So I could understand the sizeof X is 1. I know the size of Y and Z will not be as there will be virtual_pointer added to it. But 8? I dont get this. Can somebody explain?

like image 759
user1429322 Avatar asked Oct 01 '13 03:10

user1429322


1 Answers

It depends on the implementation in your compiler. Say, I got 1, 8, 8, 16 on GCC.

For the Y class, it may create a vtable for virtual base X plus 1 byte for the empty class body. After 4-byte alignment, it makes 8 bytes in total.

UPD: Also it may depend on whether you compile for 32 or 64 bit architecture. vtable pointer on a 64bit platform will take 8 bytes, hence the sizes of Y and Z.

So the complete answer on your question depends on the compiler and the target platform.

like image 107
Karadur Avatar answered Oct 19 '22 11:10

Karadur