1

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

#include <iostream>

class C
{
};

int main()
{
    std::cout << sizeof(C) << std::endl;

    return 0;
}

output: 1

Why 1, but not zero ?

Community
  • 1
  • 1
Evgenii
  • 21
  • 1

3 Answers3

4

Because the C++ standard requires all objects to have a nonzero size. This helps ensure that every object has a unique address.

dan04
  • 87,747
  • 23
  • 163
  • 198
  • Can you quote a reference. I ask because I thought the standard says that each object must have a unique address. The easy way for the compiler to guarantee this is to make each object have a size of at least one. But I could be wrong. – Martin York Jun 28 '10 at 17:58
1

The c++ standard says that every class/struct must have at least 1 byte.

adf88
  • 4,277
  • 1
  • 23
  • 21
  • Not universally true. Only most derived objects need have non-zero size. Instances of classes that are base class subobjects may have zero size. – CB Bailey Jun 28 '10 at 13:24
  • 1
    Base class is part of derived class, as a whole they must have at least 1 byte. You cannot divide an object to derived/base parts, all belong to one class - derived. – adf88 Jun 28 '10 at 13:44
  • Lets talk about objects, not classes. A base class subobject is part of a more derived object but you can and people frequently do divide it into base and derived types. If you pass a derived object into a function taking a reference to the base class then what is visible in the function is the base class part of the derived object. From the standard: "Base class subobjects may have zero size.". I think that's pretty clear. – CB Bailey Jun 28 '10 at 14:26
  • If you cast to a sub-object, it still has at least 1 byte. Maybe wiser would be say that if this 1 byte is not used by an empty base class it can be used by derived class. – adf88 Jun 28 '10 at 20:40