anarhikos anarhikos - 2 months ago 9
C++ Question

How to initialize a static const member in C++?

Is it possible to initialize a static const value outside of the constructor? Can it be initialized at the same place where member declarations are found?

class A {
private:
static const int a = 4;
/*...*/
};

Answer

YES you can but only for int types. If you want your static member to be any other type, you'll have to define it somewhere in a cpp file.

class A{
private:
 static const int a = 4; // valid
 static const std::string t ; // can't be initialized here
 ...
 ...
};


// in a cpp file where the static variable will exist 
const std::string A::t = "this way it works";

Also, note that this rule have been removed in C++11, now (with a compiler providing the feature) you can initialize what you want directly in the class member declaration.