sizeof class

A

asit

Please go through the following code...


#include <iostream>

using namespace std;

class Empty {};

class Derived1 : public Empty {};

class Derived2 : virtual public Empty {};

class Derived3 : public Empty
{
char c;
};

class Derived4 : virtual public Empty
{
char c;
};

class Dummy
{
char c;
};

int main()
{
cout<<"Sizeof(Empty) : "<<sizeof(Empty)<<endl;
cout<<"Sizeof(Derived1) : "<<sizeof(Derived1)<<endl;
cout<<"Sizeof(Derived2) : "<<sizeof(Derived2)<<endl;
cout<<"Sizeof(Derived3) : "<<sizeof(Derived3)<<endl;
cout<<"Sizeof(Derived4) : "<<sizeof(Derived4)<<endl;
cout<<"Sizeof(Dummy) : "<<sizeof(Dummy)<<endl;

return 0;
}


Why sizeof Derived4 is 8 bytes ?
 
G

Gerald Breuer

Am 10.10.2011 20:22, schrieb asit:
Why sizeof Derived4 is 8 bytes ?

In this case the compiler inserted a four bytes pointer (you're on
a 32-bit-environment) to the virtual base-class. That's usual with
virtual base-classes - but implementation defined.
 
A

asit

Hence the size should be 5 bytes(4 for v-pointer + 1 for char). Then why its is of 8 bytes ?
 
I

Ian Collins

On 10/11/11 08:13 AM, asit wrote:

What are you replying to? Please keep context.
Hence the size should be 5 bytes(4 for v-pointer + 1 for char). Then why its is of 8 bytes ?

The size of a class with a virtual base is implementation defined.
 
V

Victor Bazarov

On 10/11/11 08:13 AM, asit wrote:

What are you replying to? Please keep context.


The size of a class with a virtual base is implementation defined.

I am not even sure that implementation-definedness is limited to classes
with virtual bases. To OP: have you tried printing out the value sizeof
yields for a class with a single 'char' data member?

V
 
G

Gerald Breuer

Am 10.10.2011 21:13, schrieb asit:
Hence the size should be 5 bytes(4 for v-pointer + 1 for char). Then why its is of 8 bytes ?

That's also implementation-defined. But usually your compiler
adds some padding so that each elment in an array of objects
is properly aligned. I'm pretty sure the implementation of
your compiler has a #pragma pack(xyz) directive.
 
M

Markus Wichmann

Hence the size should be 5 bytes(4 for v-pointer + 1 for char). Then why its is of 8 bytes ?

Can you say padding? The alignment of the structure resulting from the
class definition would be four bytes, but it has a size of five bytes.
To enforce alignment in aggregate types, the size is adjusted to be
divisible by four.

HTH,
Markus
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,968
Messages
2,570,150
Members
46,697
Latest member
AugustNabo

Latest Threads

Top