0

Possible Duplicate:
Why is a class allowed to have a static member of itself, but not a non-static member?

This is invalid piece of code

struct a{
   a mem;    //Invalid as the compiler does not know how much memory to allocate
  };

But this is valid:

class Date{
  int d,m,y;
  static Date Default_date;  //Valid
};

How is the compiler able to know here how much memory to allocate here before the Date datatype is not even defined properly!!

Is this different from other static definitions in some sense???

Community
  • 1
  • 1
bhuwansahni
  • 1,834
  • 1
  • 14
  • 20
  • The compiler is not able to know how big a Date is when you *declare* the static member. But think about it -- it does not need to know it at this point. – Ferdinand Beyer Mar 12 '12 at 10:42
  • I **guess** the compiler won't allocate the memory for the static variable there (then INSIDE the class) but when it'll be declared. For instance fields it has to know the size of the type itself at declaration. I think it may be done by the compiler (and I wonder they don't) without too much effort, I imagine compiler gurus will come to explain... – Adriano Repetti Mar 12 '12 at 10:46

3 Answers3

7

The static members is not stored inside the class, so its size doesn't affect the total size of the class.

You will have to define the static member somewhere else, perhaps in a .cpp file. At that time the compiler will have to know the size of the class.

Bo Persson
  • 90,663
  • 31
  • 146
  • 203
5

In the first case it's invalid because it's a recursive struct with infinite size. In the second case it's ok because the actuall memory allocation happens after declarations.

Daniel
  • 30,896
  • 18
  • 85
  • 139
1

You can only use data members in a class declaration whose size is known at that point, i.e. for whom a definition already exists. The compiler needs to know how the amount of memory a class instance requires when it's being declared. You can use pointers and references to types that you [forward-]declare (these have a size of however many bits your operating system is).

A declaration of a static member is not allocated inside a member instance (this is what this use of static means), so its size only needs to be known when it's defined.

zyndor
  • 1,418
  • 3
  • 20
  • 36