In C++, static
members may not be initialized in the class body with these exceptions:
static
members ofconst
integral type can bestatic
members ofconstexpr
literal type must be
Can you explain why these exceptions?
Also, this holds:
Even if a
const static
data member is initialized in the class body, that member ordinarily should be defined outside the class definition.
This I never understood at all. What's the point of this extra definition?
Just trying to get some intuitions here.
Best Answer
Why can there be an initializer in the class definition?
Concerning the two exceptions for
const
andconstexpr
static data members:[class.static.data]/3
I.e. with an initializer, you may use them in constant expressions, e.g.
If
len
wasn't initialized in the class definition, the compiler couldn't easily know its value in the next line to define the length ofarr
.One could argue about allowing initializers for of non-
const
, non-constexpr
static data members in the class definition, but this could interfere with the initialization order:[basic.start.init]/2
That is, the order of the definitions including initializers is important. The order of (dynamic) initialization of non-local objects is only defined within a translation unit, this is another reason why there has to be a definition including initializer for non-
const
, non-constexpr
static data members.What's the point of this extra definition?
This has already been answered in the comments IMO. You might want to add the ODR, that is, as a name with external linkage, the static data member must (only) be defined in one translation unit (if it's ODR-used). It's up to the programmer to choose this translation unit.