5

Possible Duplicate:
Why aren't static const floats allowed?

Is there any reason why this is not possible in C++? It confuses me.

static const int A = 100; //no error
static const float B = 2.0f; //error, can't define this type in class definition.
Community
  • 1
  • 1
xcrypt
  • 3,276
  • 5
  • 39
  • 63
  • What the heck is ODR? :) – John Humphreys Jan 10 '12 at 23:11
  • [One Definition Rule](http://en.wikipedia.org/wiki/One_Definition_Rule). The details surrounding "ODR-use" are foggy but can be mostly generalized to needing an object's address. **EDIT:** Sorry, I misunderstood the OP to mean static data members. – ildjarn Jan 10 '12 at 23:12
  • Please show a complete minimal example that is failing for something of the form of `B`, because I'm unable to reproduce this. – bitmask Jan 10 '12 at 23:13

1 Answers1

1

Static constants of integral types can be initialized inside a class definition. That doesn't mean that the object actually exists, since you haven't provided a definition yet, but because the compiler knows the value of the object, you can sometimes get away with it.

That is, if you're not attempting to take the address of the variable or pass it by reference, but only use its value, then you don't need to provide a defintion at all, and the compiler simply substitutes the value wherever you use the variable.

C++11 introduces the constexpr keyword which allows you to do the same for a much wider variety of types.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084