The Question
Given an empty class A, what is sizeof(A)? This is a common interview question.
class A {
};
Code Verification
#include<iostream>
using namespace std;
class A {
};
struct B {
};
int main()
{
cout << sizeof(A) << endl;
cout << sizeof(B) << endl;
return 0;
}
Output:
[postgres@slpc my-doc]$ ./a.out
1
1
As shown, the size of both an empty class and an empty struct in C++ is 1.
Why 1?
This is a C++-specific behavior (in C, an empty struct has size 0, though that’s compiler-dependent). An “empty” class or struct here means one with no members at all.
In C++, an empty class or struct has size 1 (compiler-dependent). Why not 0? The C++ standard states: “no object shall have the same address in memory as any other variable.” If an empty class had size 0, then declaring an array of such objects would give every element the same address — a clear violation of the standard. To satisfy this requirement, the simplest solution is to prevent any type from having size 0. Therefore, the compiler inserts a dummy byte (some compilers may add more) into every empty class or struct, ensuring a non-zero size and thus guaranteeing that distinct objects have distinct addresses.