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

后端 未结 16 1613
悲&欢浪女
悲&欢浪女 2020-11-22 11:54

I was wondering what could be the size of an object of an empty class. It surely could not be 0 bytes since it should be possible to reference and

相关标签:
16条回答
  • 2020-11-22 12:45

    It is nonzero to ensure that the two different objects will have different addresses. Different objects should have different addresses, so the size of an empty class is always 1 byte.

    0 讨论(0)
  • 2020-11-22 12:47

    I think this question is only of theoretical interest but doesn't matter in practice.

    As already pointed out by others, deriving from an empty class doesn't do any harm, as this will not consume any extra memory for the base class portion.

    Moreover, if a class is empty (meaning that it - theoretically - doesn't need any per-instance memory, i.e. it doesn't have any non-static data members or virtual member functions) then all its member functions can just as well (and should) be defined as static. So there is no need to ever create an instance of this class.

    Bottom line: If you find yourself writing an empty class X then just make all member functions static. You then won't need to create X objects, and derived classes will not be affected in any way.

    0 讨论(0)
  • 2020-11-22 12:48

    I think that if the size of an empty class is zero it means that it does not exist. For it (class) to exist, it requires to have at least 1 byte, since this byte is the memory/reference address.

    0 讨论(0)
  • 2020-11-22 12:49

    Even though its not required to assign any memory for an empty class, but in order to make objects of empty classes, compiler assigns the minimum memory that can be assigned, which is 1 byte. This way compiler can distinguish two objects of the same empty class uniquely, and will able to assign the address of the object to a pointer of the empty class type.

    0 讨论(0)
提交回复
热议问题