I have a class
class foo {
public:
foo();
foo( int );
private:
static const string s;
};
Where is the best place to initialize the string s
in the source file?
This question is related to
c++
static
initialization
constants
Static members need to be initialized in a .cpp translation unit at file scope or in the appropriate namespace:
const string foo::s( "my foo");
In a translation unit within the same namespace, usually at the top:
// foo.h
struct foo
{
static const std::string s;
};
// foo.cpp
const std::string foo::s = "thingadongdong"; // this is where it lives
// bar.h
namespace baz
{
struct bar
{
static const float f;
};
}
// bar.cpp
namespace baz
{
const float bar::f = 3.1415926535;
}
Only integral values (e.g., static const int ARRAYSIZE
) are initialized in header file because they are usually used in class header to define something such as the size of an array. Non-integral values are initialized in implementation file.
Since C++17 the inline specifier also applies to variables. You can now define static member variables in the class definition:
#include <string>
class foo {
public:
foo();
foo( int );
private:
inline static const std::string s { "foo" };
};
Source: Stackoverflow.com