Why I cannot initialize a static const char* in the header file?
In my code I have in my Class header:
static const char* xml_ID_TAG;
and in the cpp:
const char* Class::xml_ID_TAG = "id";
The xml_ID_TAG variable contains the attribute string of an XML document.
Since it's static, const, primitive type (char*), etc… I can't figure out why the compiler forbid to write something like:
static const char* xml_ID_TAG = "id";
I'm using MSVC2013 compiler, giving for the example above the error: "Error: a member with an in-class initializer must be const"
Best Answer
Generally speaking you must define your static members in precisely one translation unit, and the language helps to enforce this by prohibiting you from writing an initialiser for such a member inside the surrounding class definition:
However, a special exception is made for constants, for convenience:
Note that in most cases you still need to define the constant (in your .cpp file would be the best place):
Now, your member is not an
int
and even aconst char* const
is not of an "integral type":but it is of a "literal type"; the upshot for you is that if you write it like this:
you should be okay. (Note that you will still need to define it, until C++17.)
This probably makes more sense anyway: why would you want to change the pointer?