2

I was looking up how to add static consts, the other day, to a class. I noticed that a lot of the examples were showing...

(We'll say public, for the heck of it)

test.h

class A {
public:
  static const int HELLO_WORLD=1;
};

However, I wanted to define a string and this didn't compile.

test.h

class A {
public:
  static const std::string HELLO_WORLD="WORLD HELLO";
};

After some research, I found out for non ints it was different. I had to declare them in the header, but set their value in the cpp file.

test.h

class A {
public:
  static const std::string HELLO_WORLD;
};

test.cpp

#include "test.h"
const std::string A:HELLO_WORLD = "WORLD HELLO";

I could only find answers on how to resolve it, but not actually why it needs to be like that... MY QUESTION is why does it have to be like that, and why are ints allowed to be declared + set?

Also is there a better way to do this in c++11/c++14? (Might as well ask)

Taztingo
  • 1,915
  • 2
  • 27
  • 42
  • dupe/related: http://stackoverflow.com/questions/3025997/defining-static-const-integer-members-in-class-definition – NathanOliver Feb 10 '16 at 13:20
  • 3
    I believe the restriction is necessary due to non-pod types having constructors which can do nasty things like throw exceptions. Simply put, the language would not work well is such restrictions were relaxed. – Bathsheba Feb 10 '16 at 13:21
  • 1
    It is the integral types that are different. That's the exception. You have to define the static members somewhere, *except* when declaring a `static const` member of an integral type (and never use its address). – Bo Persson Feb 10 '16 at 14:50

1 Answers1

4

Stroustrup: "In C++98, only static const members of integral types can be initialized in-class, and the initializer has to be a constant expression. These restrictions ensure that we can do the initialization at compile-time."

Try this:

class A {
public:
  constexpr static const char *HELLO_WORLD="WORLD HELLO";
};
zdf
  • 4,382
  • 3
  • 18
  • 29