1

If sizeof empty class is 1 byte then why is sizeof class having int data member not 5 bytes?

class A
{
    int a;
};

class B
{
};    

int main()
{
  std::cout << sizeof(A)<< ":" << sizeof(B) << "\n";
}

I know the expected output is 4 : 1 but just want to know why sizeof(A) is 4 byte not 5 byte. what happens to that 1 byte which helps to distinguish different object address?

melpomene
  • 84,125
  • 8
  • 85
  • 148

2 Answers2

1

If a class has no data members, the compiler pretends it contains an invisible member variable of type char, which gives it a size of 1.

In the case of your class A, there is a data member (int a;), so this special case doesn't apply. Nothing is added.

The special case is only needed because otherwise the compiler could place multiple zero-size objects at the same memory location. But if a class has data members, its size can't be zero, so nothing special happens.

melpomene
  • 84,125
  • 8
  • 85
  • 148
1

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.

eerorika
  • 232,697
  • 12
  • 197
  • 326