what is the size of empty class in C++,java?

Short Answer for C++:

The C++ standard explicitly says that a class can not have zero size.

Long Answer for C++:

Because each object needs to have a unique address (also defined in the standard) you can’t really have zero sized objects.
Imagine an array of zero sized objects. Because they have zero size they would all line up on the same address location. So it is easier to say that objects can not have zero size.

Note:

Even though an object has a non zero size, if it actually takes up zero room it does not need to increase the size of derived class:

Example:

#include <iostream>

class A {};
class B {};
class C: public A, B {};

int main()
{
     std::cout << sizeof(A) << "\n";
     std::cout << sizeof(B) << "\n";
     std::cout << sizeof(C) << "\n";  // Result is not 3 as intuitively expected.
}

g++ ty.cpp
./a.out
1
1
1

Leave a Comment