Why is the size of an empty class in C++ not zero? [duplicate]

Possible Duplicate:
C++: What is the size of an object of an empty class?

Why does the following output 1?

#include <iostream>

class Test
{
};

int main()
{
    std::cout << sizeof(Test);
    return 0;
}

The standard does not allow objects (and classes thereof) of size 0, since that would make it possible for two distinct objects to have the same memory address. That's why even empty classes must have a size of (at least) 1.


To ensure that the addresses of two different objects will be different. For the same reason, "new" always returns pointers to distinct objects.

See Stroustrup for complete answer.


The C++ standard guarantees that the size of any class is at least one. The C++ standard states that no object shall have the same memory address as another object. There are several good reasons for this.

  1. To guarantee that new will always return a pointer to a distinct memory address.

  2. To avoid some divisions by zero. For instance, pointer arithmetics (many of which done automatically by the compiler) involve dividing by sizeof(T).

Note however that it doesn't mean that an empty base-class will add 1 to the size of a derived class:

struct Empty { };

struct Optimized : public Empty {
    char c;
};

// sizeof(Optimized) == 1 with g++ 4.0.1

Bjarne Stroustrup talks about this too.