tags:

views:

132

answers:

4

Possible Duplicate:
Can sizeof return 0 (zero)

Is there a legal way to define type with zero-size in C++?

+7  A: 

No. Even a struct with no members has a size.

sje397
but it may be optimized away...
flownt
@flownt with emphasis on *"may"* -- there are certain specific circumstances where such optimisation may be used (e.g. empty sized base class optimisation).
Richard
@flownt: It cannot be optimized away to change the answer to the question: *you cannot define a type with zero size*, even if a subobject in a bigger object may be optimized away.
David Rodríguez - dribeas
+2  A: 

No, a complete object cannot have a zero size. The reason is the following. Suppose that X is a class/struct with zero size. And you declare an array of X objects:

X arr[10];

the rule is that *(arr+3) must be the fourth element, but if sizeof(X)==0 then arr, arr+1 and all others will be equal!!!.

There is one case when a subobject can be of zero size, that is, a base-class subobject. Namely, if you derive class Y from X, where X is an empty class with size, say, 4, then the X subobject in Y may have 0 size.

HTH

Armen Tsirunyan
An empty *derived* class can also not add to the size of the class.
visitor
for the derivite classes, this is a good read: http://www.cantrip.org/emptyopt.html
Necrolis
+1  A: 

C++ Standard.

1.8.5. Unless it is a bit-field (9.6), a most derived object shall have a non-zero size and shall occupy one or more bytes of storage. Base class sub-objects may have zero size. An object of POD type (3.9) shall occupy contiguous bytes of storage.

9.6.2. A declaration for a bit-field that omits the identifier declares an unnamed bit-field. Unnamed bit-fields are not members and cannot be initialized. As a special case, an unnamed bit-field with a width of zero specifies alignment of the next bit-field at an allocation unit boundary. Only when declaring an unnamed bit-field may the constant-expression be a value equal to zero.

Keynslug
+2  A: 

The only legal way to make a type have zero size, is to make it the base of a type that has a size.

struct A { };

int cba = sizeof(A); // 1

struct B : A {
  int32_t b;
};

int cbb = sizeof(B); // 4 - implying no storage for A.
Chris Becke