why is the size of an empty class 1 byte ? does the compiler add some null byte ?

Dani AI

Generated

asked why an empty class appears to take 1 byte; and pointed to the canonical explanation. The following tight clarification covers what the C++ language requires, what compilers commonly do, and practical checks to use today.

Compilers are allowed one important optimization: empty base class optimization (EBO). When an empty class is used as a base, many compilers may place that base subobject so it does not add storage to the derived object. By contrast, standalone empty objects and empty data members generally show nonzero sizeof results on typical implementations. For the language-level rules and the optimization behavior, see the cppreference pages on EBO and sizeof: empty base optimization and sizeof operator.

Practical tips: use the type trait std::is_empty<T> to detect empty types at compile time (std::is_empty). If you depend on layout or minimum size (for wire formats, ABI, or packing), do not rely solely on sizeof; test on your target compilers and ABIs. Also remember virtual functions, virtual bases, alignment, and multiple inheritance can change size in ways EBO does not remove.

Recommended Answers

All 2 Replies

That's the way it is. The compiler adds a padding byte.

The reason is that each element of an array is required to have a distinct address, and the size of an array with n elements is computed as n*sizeof(element). This would not work if sizeof(element) could yield a zero value ....

why is the size of an empty class 1 byte ? does the compiler add some null byte ?

Stroustrup's C++ Style and Technique FAQ

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.