C++ Static Const Member Variable

An example of using static const member variables in C++ is shown below with common types (integer, array, object). Only one copy of such variable is created for its class. The variable cannot be modified (it is a constant) and is shared with all instances of this class.

X.h
#include <string>


class X
{

  public:
  
    static const int    A = 10;
    
    static const char*  B;
    
    static const int    C[5];
    
    static const float  D;
    
    static const std::string E;
    
    static const std::string F[2];

};




X.cpp
#include "X.h"

using std::string;





const int    X::A;

const char*  X::B   = "hello";

const int    X::C[] = {0,1,2,3,4};

const float  X::D   = 7.0f;

const string X::E   = "ABC";

const string X::F[] = {"ABC","DEF"};

namespace
{
    const int G = 10; // Private
}

Do not omit the "static" keyword

"const" does not mean "static const". "static" keyword is necessary. Const by itself does not imply static inside a class. Const member variable can have different values for each instance. Each instance's non-static constants may be initialized to different values at runtime from the constructor's initializer list.

Only "int" is special

C++ standard says only "static const int" and "static const enum" can be initialized inside class definition. For more, refer [C++11: 9.4.2/3] and [C++03: 9.4.2/2].

Do not use before main()

If a static const member variable is initialized to a static const member variable of another class before the constructor is called, initialization is not guaranteed to work.

Y.h
class Y
{
  public:
  
    static const float H;

};

Y.cpp
#include "Y.h"
#include "X.h"

const float Y::H = X::D;
// H not guaranteed to be D's value



For more, refer "static initialization order fiasco."