The class declaration should be in the header file, or in the source file, if the class is not used in other files.
// foo.h
class foo
{
private:
static int i;
};
However, the initialization should be in the source file.
// foo.cpp
int foo::i = 0;
If the initialization is in the header file, then each file that includes the header file will have a definition of the static member. Thus during the link phase, you will get linker errors as the code to initialize the variable will be defined in multiple source files.
The initialization of the static int i
must be done outside of any function.
Note: Matt Curtis: points out that C++ allows the simplification of the above if the static data member is of const integer type (bool
, char
, char8_t
[since C++20], char16_t
, char32_t
, wchar_t
, short
, int
, long
, long long
, or any implementation-defined extended integer types, including any signed, unsigned, and cv-qualified variants.). You can then declare and initialize the data member directly inside the class declaration in the header file:
class foo
{
private:
static int const i = 42;
};
inline static int x[] = {1, 2, 3};
. See en.cppreference.com/w/cpp/language/static#Static_data_members – Cailly