Invalid in-class initialization of static data member of non-integral type ‘const char*’

From Cppsyntax

Jump to: navigation, search

You can get the error

 invalid in-class initialization of static data member of non-integral type ‘const char*’

if you try to first assign the value of a static variable inside a class/outside of a method.

@@@ CHECK @@@

You are only allowed to first assign variables that are enumeration types or"integral" types -- int, char, long, etc -- inside a class definition. Char* is not an integral type, so you can only assign to it in global scope.

See also cannot declare member function ‘static int Foo::bar()’ to have static linkage

WRONG

 class Foo
 {
   public:
     static char bar[10] = "abcdefghi";
   // stuff
 };

RIGHT

 class Foo
 {
   public:
     static char bar[10];
   // stuff
 };
 char *Foo::bar = "abcdefghi";

If you put your class definition in a .h file, you must put the initialization in the .cc file, not the .h file.


Note that you can completely sidestep this issue by putting your constant into a function:

ALSO WORKS

 class Foo
 {
   public:
     static const char* bar()
     {
       return "abcdefghi";
     };
 };


Other sources

Personal tools