Search

Sponsored Links

Meta

Categories

Archives

Recent Posts

RSS Feeds

21
Dec

Size of an empty class

Related Blog Items

In brief: 

The size of an empty class is non zero, the reason for this is, if size of empty class is zero, it violates C++ object definition, the object definition says that "object should have unique identity, state, behavior". How can an empty class object make sure of unique identity if the size of object is zero (because there is possibility of assigning same address). So, in order to achieve this, it (compiler) needs to assign distinct addresses for objects, which essentially requires memory to be allocated, if you do that obviously you get non-zero size for empty class.

here is the story.. :-)

An empty class doesn’t have any data members or member functions. Therefore, the size of an instance is seemingly zero. However, C++ guarantees that the size of a complete object is never zero. Consider the following example:

class Empty {};
Empty e; // e occupies at least 1 byte of memory

If an object is allowed to occupy zero bytes of storage, its address can overlap with the address of a different object. The most obvious case is an array of empty objects whose elements all have an identical address. To guarantee that a complete object always has a distinct memory address, a complete object occupies at least one byte of memory. Non-complete objects — for example, base class subobjects in a derived class — can occupy zero bytes of memory.

[tags]sizeof an empty class, empty class size, class sizeof, c++ empty class size [/tags]
[tags]sizeof an empty class, empty class size, class sizeof, c++ empty class size [/tags]

Popularity: 6%

You need to log on to convert this article into PDF


Related Blog Items

No Comments

No comments yet.

Leave a comment

*
To prove you're a person (not a spam script), type the security word shown in the picture.
Anti-spam image