Reputation: 414
I have two classes as follows
class A
{
};
class B
{
int a[];
};
int main()
{
cout << sizeof(A) <<endl; //outputs 1
cout << sizeof(B) <<endl; //outputs 0
return 0;
}
I am familiar that size of empty class is 1,but why is the size of class B coming to be ZERO??
Upvotes: 9
Views: 229
Reputation: 114461
The size of an empty class is not 1. It's AT LEAST 1 in a C++ system.
The reason is that you need to be able for example to allocate an instance with new
and having a non-null pointer directed at it.
The second case instead is simply invalid C++.
Often compiler makers take some freedom by allowing non-standard "extensions" by default and try to make you use them unconsciously (a paranoid would say to lock you in by making your code unportable to other compilers).
Upvotes: 2
Reputation: 340178
GCC permits zero length arrays as an extension: http://gcc.gnu.org/onlinedocs/gcc/Zero-Length.html
And:
As a quirk of the original implementation of zero-length arrays, sizeof evaluates to zero.
Upvotes: 6
Reputation: 361302
Your code is ill-formed as far as C++ language is concerned. In particular, the class B
shouldn't compile in C++ Standard Conformant compiler. Your compiler has either bug, or it provides this feature as extension.
GCC with -pedantic-errors -std=c++11
gives this error:
cpp.cpp:18:11: error: ISO C++ forbids zero-size array 'a' [-Wpedantic]
int a[];
^
Upvotes: 4