Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

With the code:

#include <iostream>

class A {};
class B { char x; };

int main()
{
    std::cerr << sizeof(A) << " " << sizeof(B) << std::endl;
}

I know that it's a common interview question to ask the size of an empty class - and I know the answer is one.

My question is... what is held in that "1" byte for an empty class (I'm guessing its empty), and what does the compiler do internally to make it so that sizeof B is the same as sizeof A in this case?

I'd like to fully understand it rather than just know the answer.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
279 views
Welcome To Ask or Share your Answers For Others

1 Answer

This isn’t really a meaningful question: The runtime just marks the one byte as occupied so that no other object will be allocated at its position. But there isn’t anything “held” there to occupy the byte.

The only reason for this rule is that objects must be uniquely identifiable. An object is identified by the address it has in memory. To ensure that no two objects have the same address (except in the case of base class objects), objects of empty classes “occupy” memory by having a non-zero size.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...