Hi,
Can anybody explain why size of a Empty class is 1 byte?
Hi,
Can anybody explain why size of a Empty class is 1 byte?
Because if the size is zero, how else could you make this [silly] example code work?
If the size is zero, then all c elements would have the same address.Code:class c { }; c arr[10]; c *p; ... if (p != &arr[0]) ...
What difference does it make to you?
--
Mats
Compilers can produce warnings - make the compiler programmers happy: Use them!
Please don't PM me for help - and no, I don't do help over instant messengers.
It actually comes down to the fact that the unit in the C memory model is the char (which has sizeof 1 by definition), and that n*sizeof(anything) is the size of an array of n anything's. That computation would not work if sizeof(anything) could be zero.
More precisely, sizeof a structure type provides the total size in bytes of the structure, including data it contains and any internal or trailing padding (which are used to ensure alignment of data in a manner that is suitable for the target machine). The one byte you are seeing means that your compiler adds one byte padding to an empty struct (the actual amount of padding depends on the implementation).
Don't worry, it doesn't take up any space when used purely as a base class for another class. Look up "Empty base member optimization".
My homepage
Advice: Take only as directed - If symptoms persist, please see your debugger
Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"
Every object must have a unique address. So It Is Written In The Standard. But if an object occupies no space at all, how can it have an address? Therefore it must occupy space.
Also, iMalc's comment about empty base optimization is pertinent. Same goes for empty objects as members of other objects.