Size of empty classes
Thursday, September 2nd, 2010Little trivia about empty classes…. Here’s the setup:
Question: what’s the size of Test0? What’s the size of Test1?
It’s a relatively well known fact that embedded empty classes are not actually free, and add 1 byte to the class containing them. So, knowing this, it shouldn’t be a surprise that sizeof(Test0)==2.
A more surprising fact, maybe, is that sizeof(Test1)==1. Yep, not free either, and a different size from Test0. It has to do with an obscure rule saying that the addresses of base classes must be different, or something. Can’t remember. Still, you need to keep this in mind if you don’t want to discover weird “ghost bytes” in your binary-serialized data.
Oh well.