3

I know how to initialize a static member that's not an integer, 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, like you can with an integer member, 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?

0

2 Answers 2

6

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".

1

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); }
}
1
  • 1
    You can initialize a static const integer type within the class as OP shows. I think the question is about other types.
    – UncleBens
    Commented Aug 26, 2010 at 15:43

Not the answer you're looking for? Browse other questions tagged or ask your own question.