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