0

Consider the following class in which I define 2 static variables with constant value and initialisation upon declaration.

Both variable are primitive, but for the string initialisation I get the following error when compiling with LLVM (clang) Non-const static data member must be initialized out of line even though its type is preceded by const. In visual studio, the same code passed compilation.

perhaps anybody can explain this discrepancy ?

class my class 
{
public:
    // the variable in this line is recognised as non-const. 
    // Therefore, it doesn't allow initialisation.
    static const wchar_t* bla = L"000111"; 
    
    // this line compiles perfectly well. 
    static const int bla2 = 128; 
}
arnt
  • 8,949
  • 5
  • 24
  • 32
Zohar81
  • 4,554
  • 5
  • 29
  • 82
  • Just because something "is preceded by `const`" doesn't make it `const`. C++ is not that simple. `const wchar_t *` is a pointer to constant `wchar_t`s. It is not, itself, a `const`. There is a big difference between a pointer to something that's `const`, and a `const` pointer to something. Two completely different things. – Sam Varshavchik Nov 08 '20 at 12:04
  • @SamVarshavchik, thanks for you comment. is there any way to make this pointer `const` rather than pointing to `const wchar_t*` ? – Zohar81 Nov 08 '20 at 12:38
  • Of course there is. This should be explained in a chapter in every C++ textbook that explains how types are declared in C++. Unfortunately, Stackoverflow is not a replacement for a C++ textbook, and it wouldn't make any sense to copy/paste entire chapters from textbooks, here. I expect that every textbook will discuss the three different ways to use the `const` keyword: a constant object or a pointer, a pointer to a constant object, and a constant class method. You could also try searching Stackoverflow, you might also find previous questions regarding this topic. – Sam Varshavchik Nov 08 '20 at 13:27

0 Answers0