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

后端 未结 16 1664
悲&欢浪女
悲&欢浪女 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: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.

提交回复
热议问题