0

In the code below is the line static const int maximum = 42 in the Fred.h file not sufficient as a definition for the static member given that we initialize it with a value? Why do we need the const int Fred::maximum line in Fred.cpp.

//Fred.h 
   class Fred {
    public:
      static const int maximum = 42;
      ...
    };

     // Fred.cpp

    #include "Fred.h"

    const int Fred::maximum

;

vkaul11
  • 4,098
  • 12
  • 47
  • 79
  • I have no problems compiling and printing `Fred::maximum` without that line in .cpp (gcc 4.7.2 C++11 mode) – Alexander Malakhov Mar 06 '13 at 02:59
  • 4
    summarily, the reason is that a const is still a variable - it needs memory allocated for it (you might take the address), and which of the translation units that include Fred.h should be responsible for that? C++ decides that it's the translation unit containing the *definition* that actually causes reservation of the memory for the variable. – Tony Delroy Mar 06 '13 at 03:00
  • It depends on how you use that constant. Similar situation (for an enum): http://stackoverflow.com/a/15113748/777186 – jogojapan Mar 06 '13 at 03:03
  • @TonyD well, to be fair, it could be made a weak symbol just like templated static const variables are – Stephen Lin Mar 06 '13 at 03:04
  • @StephenLin: true - I wonder if weak symbols were commonly supported by linkers back when the decisions re statics were taken.... – Tony Delroy Mar 06 '13 at 04:08
  • @TonyD it doesn't seem like a bigger problem than taking the address of an inline function or creating virtual tables for header-only classes, both of which I'm pretty sure were supported forever, so honestly I don't really understand why they made this restriction. – Stephen Lin Mar 06 '13 at 04:49

0 Answers0