Why is sizeof empty class 1?
This is because every object is guaranteed to have a unique address (exceptions apply). In order for an array of N objects to have N objects with unique address, they must be stored 1 byte apart. By definition, this distance is the size of the class. 1 byte is the minimum possible size for any type.
Classes can contain padding that is not part of any sub-object. An empty class contains a single byte of padding.
then why sizeof class having int data member is not 5 bytes?
Because a non-empty class doesn't need padding to guarantee the uniqueness of the address of the object. In particular, a class with a single int
member doesn't require any padding.
Non-empty classes may need padding for another reason though: Alignment. For example, a class:
class C {
alignas(4) int i;
char c;
};
will have the size 8 (3 bytes padding) in order to satisfy the alignment requirement of the member i
.