3

If I declare for instance

static const float PI = 3.14159265358979323846264338327950288419716939937510f;

to be the member of some Math class, it tells me:

a member of type "const float" cannot have an in-class initializer

so I have to set it in the .cpp file:

const float Math::PI = 3.14159265358979323846264338327950288419716939937510f;

yet when I do the same with an unsigned integer instead of float, it doesn't recognize it as a compile-time constant and doesn't let me use it as one, unless I set the value inside the class header(something which I'm not allowed to do with a float)

ulak blade
  • 2,515
  • 5
  • 37
  • 81
  • If its value never changes (and is probably in a .h file) why not just use `#define PI 3.1415926535`? – Zach Stark Oct 29 '13 at 23:47
  • 2
    The only sensible answer to "Why" is "because that's what the standard says". There isn't necessarily a "sensible" reason, that's just how it came about. – Kerrek SB Oct 29 '13 at 23:47
  • If you use `static any_type my_varname;` in a class declaration, the variable has to be declared as global in the cpp file. The attribute isn't member of an instance of the class, but of the class. – Pierre Emmanuel Lallemant Oct 29 '13 at 23:47
  • @KerrekSB: so just to be clear, is it specifically this question about C++ language design for which you are certain that no rational explanation exists for the choices made, or all questions about C++ language design? ;-) The standard isn't a Burroughs cut-up, for all that it might read like one at times. – Steve Jessop Oct 30 '13 at 00:41
  • @SteveJessop: There's probably a genuine reason (something about integers being portable and easy to implement and optimize) and it seemed like a good idea at the time, but it's hard to justify this arbitrary choice from an abstract design point of view. Which is presumably why this was fixed in C++11... – Kerrek SB Oct 30 '13 at 01:29
  • @KerrekSB: my guess always was that the language (pre-standard, even) was supporting cross-compilers that can't emulate the target's floating point. So all forms of "compile-time constant" floating-point values were excluded in C, and C++ introduced the syntax for static integral data members only in a case that uses and is relevant to ICEs. But it's pretty extreme to defer even the rounding of literals to runtime. – Steve Jessop Oct 30 '13 at 01:41

0 Answers0