tags:

views:

67

answers:

2

Hi All,

I know how to initialize a static member, but I'm wondering, what is the rationale behind the syntax for this? I'd like to be able to just put the value in the class, a la:

class A {
  static const int i = 3;
};

I realise this could mean more rebuilding if I change the value since it's a change in the header - but in some cases that's pretty unlikely - and just as bad as changing a #define in the header anyway.

It doesn't seem like something that would be terribly hard for the compiler to understand. Are there technical reasons why it works the way it does? Or is it just a case of the compiler enforcing the good practice of separating the implementation from the definition?

+5  A: 

Because that is the class declaration. You don't have any object yet.

You need to actually define the value somewhere --- somewhere specific.

Since it is static it's actually taking up space somewhere. But, since the .H file which has that declaration can be #included in many source files, which one defines holds the actual space it is using? Having the compiler automatically define the space in every object file and having the linker sort it out would be a violation of the "One Definition Rule".

James Curran
+1  A: 

A static class member has linkage, so it needs to be in a source file. Just because you declare it const doesn't mean it really can't change (please look up volatile for example).

This might help you:

class A {
    enum { i = 3 }; // use an enum to set a constant value in the class declaration
    void f() { int k = int(i); }
}
Gabriel Schreiber
You *can* initialize a static const *integer type* within the class as OP shows. I think the question is about other types.
UncleBens