C++ where to initialize static const

C++StaticInitializationConstants

C++ Problem Overview


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?

C++ Solutions


Solution 1 - C++

Anywhere in one compilation unit (usually a .cpp file) would do:

foo.h

class foo {
    static const string s; // Can never be initialized here.
    static const char* cs; // Same with C strings.

    static const int i = 3; // Integral types can be initialized here (*)...
    static const int j; //     ... OR in cpp.
};

foo.cpp

#include "foo.h"
const string foo::s = "foo string";
const char* foo::cs = "foo C string";
// No definition for i. (*)
const int foo::j = 4;

(*) According to the standards you must define i outside of the class definition (like j is) if it is used in code other than just integral constant expressions. See David's comment below for details.

Solution 2 - C++

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" };
};

Solution 3 - C++

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;
}

Solution 4 - C++

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");

Solution 5 - C++

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionThomasView Question on Stackoverflow
Solution 1 - C++squelartView Answer on Stackoverflow
Solution 2 - C++plexandoView Answer on Stackoverflow
Solution 3 - C++GManNickGView Answer on Stackoverflow
Solution 4 - C++Michael BurrView Answer on Stackoverflow
Solution 5 - C++Behnam DezfouliView Answer on Stackoverflow