c++staticinitializationconstantsstatic-members

Where should a static const data member be defined?


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?


Solution

  • 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.