Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the size of this class and Why?

Tags:

c++

class

sizeof

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??

like image 451
pushE Avatar asked Jun 27 '13 05:06

pushE


2 Answers

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.

like image 77
Michael Burr Avatar answered Sep 30 '22 16:09

Michael Burr


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[];
           ^
like image 33
Nawaz Avatar answered Sep 30 '22 14:09

Nawaz