What is the size of an empty class in C++ and Java?
Why is it not zero?
sizeof();
returns 1 in the case of C++.
It is known that size of an empty class is not zero. Generally, it is 1 byte.
The size of an empty class is not zero. It is 1 byte generally.
A simple empty class of java supports legacy, as it automatically acquires object class, therefore can produce the functionality described in the object hierarchy. It automatically generates a fault constructor inside the class with a blank description.
Java Class Any class in Java is nothing but an object with a mix of all mentioned components: header (8 or 12 bytes for 32/64 bit os). primitive (type bytes depending on the primitive type). object/class/array (4 bytes reference size).
The C++ standard explicitly says that a class can not have zero size.
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.
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
In the Java case:
sizeof
operator.Instrumentation
or 3rd party libraries) that will give you a number, but the meaning is nuanced1; see In Java, what is the best way to determine the size of an object? The size of an instance of an "empty class" (i.e. java.lang.Object
) is not zero because the instance has implicit state associated with it. For instance, state is needed:
Current Hotspot JVMs use clever tricks to represent the state in an object header that occupies two 32 bit words. (This expands in some circumstances; e.g. when a primitive lock is actually used, or after identityHashCode()
is called.)
1 - For example, does the size of the string object created by new String("hello")
include the size of that backing array that holds the characters? From the JVM perspective, that array is a separate object!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With