class layout

T

thomas

class A{
protected:
int a;
char b;
};

class B: public A{
protected:
char c;
};

class A size is 8 bytes with 3 bytes as alighment padding;
class B size is 12 bytes with another 3 bytes padding.

Why doesn't B pack the two "char" into one 4 bytes?
 
S

SG

class A{
protected:
    int a;
    char b;

};

class B: public A{
protected:
    char c;

};

class A size is 8 bytes with 3 bytes as alighment padding;
class B size is 12 bytes with another 3 bytes padding.

Why doesn't B pack the two "char" into one 4 bytes?

Ask your compiler vendor. The C++ standard allows this kind of packing
as far as I can tell.

I just tested it with GCC C++ compiler on a 32bit Linux system: sizeof
returns 8 for both classes.

Cheers!
SG
 
D

doublemaster007

class A{
protected:
    int a;
    char b;

};

class B: public A{
protected:
    char c;

};

class A size is 8 bytes with 3 bytes as alighment padding;
class B size is 12 bytes with another 3 bytes padding.

Why doesn't B pack the two "char" into one 4 bytes?

Which compiler did u test the code with??
 
F

Fraser Ross

"thomas"
class A{
protected:
int a;
char b;
};

class B: public A{
protected:
char c;
};

class A size is 8 bytes with 3 bytes as alighment padding;
class B size is 12 bytes with another 3 bytes padding.

Why doesn't B pack the two "char" into one 4 bytes?

Assignments through pointers to base classes are more complicated to
implement.

Fraser.
 
T

thomas

Ask your compiler vendor. The C++ standard allows this kind of packing
as far as I can tell.

I just tested it with GCC C++ compiler on a 32bit Linux system: sizeof
returns 8 for both classes.

Cheers!
SG- Hide quoted text -

- Show quoted text -

I'm using the visual studio c++ 2005 IDE.
The result is 8, and 12 respectively.
The example is cited from the book "inside the c++ object model".
As you pointed out, the result depends on compiler, I get puzzled that
the book may also depends on compiler, which means some content of the
book is not always reliable.
 
F

Fraser Ross

On what page does it say that a B object could be 8 bytes? P86 explains
why it is 12.

Fraser.
 

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

No members online now.

Forum statistics

Threads
474,164
Messages
2,570,897
Members
47,439
Latest member
shasuze

Latest Threads

Top