what is size of empty class and difference between union, structure and class in c++ ?

淺唱寂寞╮ 提交于 2019-12-04 20:14:53

C++ Standard standard specify's that the size of an Empty class should be Non-Zero.
Usually, it is 1 byte on most systems.

In Bjarne Stroustrup's words, the size is non-zero "To ensure that the addresses of two different objects will be different."

The size is 1 on most systems because the alignment rules don't matter as the entry of the class name is made in symbol table just to obtain an unique address.

For Standerdese fans:
C++03 Standard Section 9: Classes, Para 2:

Complete objects and member subobjects of class type shall have nonzero size. 94)

class == struct the only difference is that in a struct, all members i.e. ivars and methods are public by default.

static members i.e. variables or methods, are not part of the class/struct in the sense they do not belong to a particular instance. so a sizeof will not include them.

union is not a class nor struct, Union is used to map a struct to a particular memory layout.

to get the size just do a sizeof() of an instance variable and you will see.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!