Zero class size.

Aug 17, 2009 at 10:38am
Hey.!!

could someone explain me the strange code below. Why is the size of a class zero..??

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
using namespace std;

class Base
{
private:
   char m_Name[]; // is this allowed?? its compiling for me on gcc
};

int main()
{
   cout<<"Size of class Base = "<<sizeof(Base)<<endl;
   Base arr[5];
   cout<<"Address of object 0 = "<<&arr[0]<<endl;
   cout<<"Address of object 1 = "<<&arr[1]<<endl;
   cout<<"Address of object 2 = "<<&arr[2]<<endl;
   cout<<"Address of object 3 = "<<&arr[3]<<endl;
   cout<<"Address of object 4 = "<<&arr[4]<<endl;
   return 0;
}


output i get is :
Size of class Base = 0
Address of object 0 = 0xbfffef58
Address of object 1 = 0xbfffef58
Address of object 2 = 0xbfffef58
Address of object 3 = 0xbfffef58
Address of object 4 = 0xbfffef58


Aug 17, 2009 at 11:36am
It shouldn't be allowed, but often is for historical reasons.

The correct syntax is char m_Name[0];

It is used to indicate that an array of some type (char in this case) follows in memory. The size isn't specified and you're expected to already know how many there are. Ideally, the entry shouldn't take any space, but be a marker in memory.

Your use of the facility is incorrect.
Topic archived. No new replies allowed.