Home > Backend Development > C++ > Why Do Empty Classes in C Have a Size of 1 Byte, Not 0 Bytes?

Why Do Empty Classes in C Have a Size of 1 Byte, Not 0 Bytes?

Barbara Streisand
Release: 2024-12-14 19:12:12
Original
166 people have browsed it

Why Do Empty Classes in C   Have a Size of 1 Byte, Not 0 Bytes?

Understanding the Size of Empty Class Objects

In C , even seemingly empty classes have a non-zero size. One might assume it would be 0 bytes, but this is not the case. This question delves into the reasons behind this behavior.

To illustrate this, consider the following program:

#include <iostream>
using namespace std;

class Empty {};

int main()
{
    Empty e;
    cerr << sizeof(e) << endl;
    return 0;
}
Copy after login

If one compiles this program, the output on various compilers (e.g., Visual C and Cygwin-g ) is consistently 1 byte. This may seem unexpected since the object contains no data members.

Why 1 Byte?

The compiler assigns a size of 1 byte to an empty class object to ensure that different objects have unique addresses. This distinction is crucial for proper memory management and avoiding aliasing issues.

Why Not 4 Bytes (Machine Word)?

One might expect the size of the object to align with the machine word size (32 or 64 bits), but this is not the case. Alignment concerns become irrelevant for empty classes because there are no data members to align. Consequently, the compiler optimizes space by assigning the minimum feasible size: 1 byte.

Non-Zero Size Justification

A size of 0 bytes would imply that two objects of an empty class could occupy the same memory location, making it impossible to distinguish between them. This ambiguity could lead to undefined behavior in the program. Therefore, a non-zero size (in this case, 1 byte) ensures unique addresses and maintains program integrity.

The above is the detailed content of Why Do Empty Classes in C Have a Size of 1 Byte, Not 0 Bytes?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template