1

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

I have a class without data as the following

class A {};

I use it to define an object

A a;

I think object "a" has an address, right? Does it occupy some memory? If so, how many bytes it occupy?

What happens if object "a" with a type void. Thanks a lot!

Community
  • 1
  • 1
user1899020
  • 13,167
  • 21
  • 79
  • 154
  • 3
    See this post: [c-what-is-the-size-of-an-object-of-an-empty-class](http://stackoverflow.com/questions/621616/c-what-is-the-size-of-an-object-of-an-empty-class) – Kim Hansson Dec 30 '12 at 16:18

2 Answers2

5

I think object "a" has an address, right? Does it occupy some memory? If so, how many bytes it occupy?

IIRC the standard mandates that every object has an address, and the minimum size of an object (as returned by sizeof) is 1. That being said, probably the optimizer will make that variable disappear (maybe unless you explicitly ask for its address).

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 subobjects may have zero size. [...]

Unless an object is a bit-field or a base class subobject of zero size, the address of that object is the address of the first byte it occupies. Two distinct objects that are neither bit-fields nor base class subobjects of zero size shall have distinct addresses.4

Note 4: Under the “as-if” rule an implementation is allowed to store two objects at the same machine address or not store an object at all if the program cannot observe the difference (1.9).

(C++11 §1.8 ¶5-6)


What happens if object "a" with a type void.

void can't be used to declare variables, since it's an "incomplete type".

The void type has an empty set of values. The void type is an incomplete type that cannot be completed.

(C++11 §3.9.1 ¶9)

Matteo Italia
  • 123,740
  • 17
  • 206
  • 299
3

Theoretically, it doesn't have to take up any memory at all. It can be optimized away alltogether.

The sizeof a class can't be 0 though, if that's what you mean. If you print out sizeof(a), you'll (most of the time) get 1 (whatever it is, it's a non-zero value).

Also, you can't have an object of type void, so the last question doesn't make sense.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625