tags:

views:

141

answers:

3

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 ?

+1  A: 

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

adf88
Not universally true. Only most derived objects need have non-zero size. Instances of classes that are base class subobjects may have zero size.
Charles Bailey
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
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.
Charles Bailey
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
+4  A: 

From Stroustrup's mouth sizeof

DumbCoder
+3  A: 

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

dan04
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