I have a question related to the initialization of static members in the header files. In the following example:
some_project.h
class MyClass
{
private:
void foo() const;
private:
static constexpr char array[] = "my array";
static constexpr const char *ptr = "my pointer";
};
some_project.cpp
constexpr char MyClass::array[];
void MyClass::foo() const
{
cout << array << ptr << endl;
}
I have to define array[]
in cpp file although it is already defined in header file, otherwise I end up with linker undefined reference
errors. However this is not happening for the pointer, ptr
is working just fine.
I know that C++ allows declarations and initialization inside class declaration in header files if members are const int type. What is the logic behind? Is that because integral data types fits into register and are inlined and therefore no additional definitions in cpp file is needed? Or is it because constexpr works as an C-style macro and is inlined and array is not?