Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static const member variable initialization

Looks like I can init a POD static const member, but not other types:

struct C {
  static const int a = 42;      // OK
  static const string b = "hi"; // compile error
};

Why?

like image 959
Deqing Avatar asked Jul 17 '14 08:07

Deqing


1 Answers

The syntax initializer in the class definition is only allowed with integral and enum types. For std::string, it must be defined outside the class definition and initialized there.

struct C {
  static const int a = 42;     
  static const string b; 
};

const string C::b = "hi"; // in one of the .cpp files

static members must be defined in one translation unit to fulfil the one definition rule. If C++ allows the definition below;

struct C {
  static const string b = "hi"; 
};

b would be defined in each translation unit that includes the header file.

C++ only allows to define const static data members of integral or enumeration type in the class declaration as a short-cut. The reason why const static data members of other types cannot be defined is that non-trivial initialization would be required (constructor needs to be called).

like image 61
Alper Avatar answered Sep 25 '22 22:09

Alper