Class Sizes?

How come a class with an integer and boolean is of size 8, when a boolean has a size of 2 and an integer has a size of 4?

for example:
1
2
3
4
5
class A{
int X;
bool Y;
};
sizeof(A); // = 8 

but when you only add an integer
1
2
3
4
class A{
int X;
};
sizeof(A); // = 4 

same thing happens whenever you have different data types but not the same, eg:
1
2
3
4
5
6
class A{
int X;
int Y;
int Z;
};
sizeof(A); // = 12 

that seems right since an integer has a size of 4, and 4*3=12 but then:
1
2
3
4
5
6
7
class A{
int X;
int Y;
int Z;
bool w;
};
sizeof(A); // = 16 

its like bool just got 3 bytes bigger O.o

its not only integer and bool, same thing happens with all other data types

This isn't really a problem for me cause a few extra bytes is nothing, but if I don't know why its happening then it means I don't know enough
IIRC, it's padding the class out to sizeof(int)
why? wouldn't that be wasting 3 bytes of memory? its not like bool uses them
Access/computation speed usually. The alignment of variables can make a difference. Padding to a boundary is pretty typical.
bool doesn't exist to save memory. It exists as a seperate type from int so you can overload on bool.

In C and earlier versions of C++ there is no bool, logical operations are of type int.
Topic archived. No new replies allowed.