Size of an empty class
Related Blog Items
- UTF8 To Unicode conversion program
- Data types in C
- C Obscurity Tests (with reasons behind them)
- C++ Advanced Tutorial - Lesson 3
- C/C++ Questions asked in various job interviews
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.
Popularity: 11%
You need to log on to convert this article into PDF
Related Blog Items - UTF8 To Unicode conversion program
- Data types in C
- C Obscurity Tests (with reasons behind them)
- C++ Advanced Tutorial - Lesson 3
- C/C++ Questions asked in various job interviews
Related Blog Items
- UTF8 To Unicode conversion program
- Data types in C
- C Obscurity Tests (with reasons behind them)
- C++ Advanced Tutorial - Lesson 3
- C/C++ Questions asked in various job interviews
No Comments
No comments yet.