Search code examples
c++staticinitializationconstants

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


Is it possible to initialize a static const data member outside of the constructor? Can it be initialized at the same place where data member is declared?

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

Solution

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