乐闻世界logo
搜索文章和话题

C ++: What is the size of an object of an empty class?

1个答案

1

In C++, even an empty class (i.e., a class with no data members and member functions) does not have a size of 0 bytes when an object is created. This is because each instance requires a unique address to distinguish them from each other. According to the C++ standard, an empty class object must occupy at least 1 byte.

For example, define an empty class:

cpp
class EmptyClass {};

Then, we can test the size of the object:

cpp
#include <iostream> class EmptyClass {}; int main() { EmptyClass obj; std::cout << "Size of object is: " << sizeof(obj) << " byte." << std::endl; return 0; }

The output of this code will be:

shell
Size of object is: 1 byte.

This indicates that even if the class has no data members or member functions, each object still occupies 1 byte of space, primarily to ensure that each object has a unique address in memory.

2024年6月29日 12:07 回复

你的答案