Static data members need an initialization outside the class declaration. This is:
struct S {
static int i;
};
int S::i = 42; // definição
This is a language restriction, following the rule of a definition (one definition rule, or ODR).
The constraint exists to prevent two or more initializations from occurring for the S::i
static member (for example, if the class is included in two distinct translation units). Note: The initialization needs to appear only in a translation unit, otherwise the behavior is undefined.
With the qualifier const
, standardization allows you to initialize the static member with some constant expression (that is, it can be initialized with a literal like 42
, but can not initialize with some value that does not result in an expression constant).
In c ++ 17 , you can use the inline
specifier to allow the initialization of the data member in the same location as your declaration:
struct S {
static inline int i = 42;
};
Here,
inline
has the same effect when applied to functions: its initialization can appear in one or more translation units (as long as they are equivalent, eg included by a
#include
directive), and only one of them will be used in fact.