sizeof an empty class object

J

JK

if i declare a class
class empty
{
};

and if i do the following

empty empt;
int iSize = sizeof(empt);
The value of iSize is 1. how the size of the empty class became 1 ?
what does that 1 byte contain ?
 
S

Siemel Naran

JK said:
if i declare a class
class empty
{
};

and if i do the following

empty empt;
int iSize = sizeof(empt);
The value of iSize is 1. how the size of the empty class became 1 ?
what does that 1 byte contain ?

Nothing important. The size is required to be anything > 0. though is
usually 1. The reason for this is that you may have an array of empty
objects, or you might want to form an address to an empty object, so the
empty object better have a size larger than zero.

But if you derive from class empty, then the size of class empty within the
entire class may be zero. This is called the empty base optimization.

Thus,

struct S : public empty {
int i;
};

cout << sizeof(int); // prints 4 on my platform
cout << sizeof(empty); // prints 1 on my platform
cout << sizeof(S); // prints 4 on my platform, not 5 or 8
 

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,731
Messages
2,569,432
Members
44,832
Latest member
GlennSmall

Latest Threads

Top