John Humphreys
John Humphreys

Reputation: 39294

Sizeof empty class

With the code:

#include <iostream>

class A {};
class B { char x; };

int main()
{
    std::cerr << sizeof(A) << " " << sizeof(B) << std::endl;
}

I know that it's a common interview question to ask the size of an empty class - and I know the answer is one.

My question is... what is held in that "1" byte for an empty class (I'm guessing its empty), and what does the compiler do internally to make it so that sizeof B is the same as sizeof A in this case?

I'd like to fully understand it rather than just know the answer.

Upvotes: 7

Views: 2239

Answers (3)

Konrad Rudolph
Konrad Rudolph

Reputation: 545588

This isn’t really a meaningful question: The runtime just marks the one byte as occupied so that no other object will be allocated at its position. But there isn’t anything “held” there to occupy the byte.

The only reason for this rule is that objects must be uniquely identifiable. An object is identified by the address it has in memory. To ensure that no two objects have the same address (except in the case of base class objects), objects of empty classes “occupy” memory by having a non-zero size.

Upvotes: 8

MSalters
MSalters

Reputation: 179809

You can often see a similar effect in classes like these :

class Foo {
  int a;
  char b;
}; // sizeof(Foo) > sizeof(int) + sizeof(char)

Not all memory in a C++ object needs to have a name. Unnames memory inside an object is commnoly called "padding". Your empty class happens to have one byte of padding. One of the most common reasons why C++ compilers insert padding is to allow use of a class in an array type.

Upvotes: -1

cprogrammer
cprogrammer

Reputation: 5675

There is no requirement in the C++ standard that an empty object should have one byte of memory occupied. It is purely based on the implementation.

EDIT: true, it's conforming ( ISO/IEC 14882 p.149 ):

9 Classes [class]
..
..
..
3 Complete objects and member subobjects of class type shall have nonzero size ...

Upvotes: 4

Related Questions