Mathew
Mathew

Reputation: 1430

C++ constant static char* array

EDIT: please note, as stated in @ThomasMatthews answer, it is better not to put data in a header. Please refer to his answer.

I would like to create a static const char* const array in the header file of a class. For example: const static char* ar[3] = {"asdf","qwer","ghjk"}; However I get an error.

Here is an example:

#include <iostream>
class test{
  static const char* const ar[3] = {"asdf","qwer","hjkl"};
}
int main(){}

and here is the error:

static data member of type 'const char *const [3] must be initialized out of line

I'd like to know if what I am trying to do is possible. I have read Defining static const integer members in class definition and the impression I got from it was that you can only do this with int. In case this is relevant I am using a mac and my g++ version is as follows:

Apple LLVM version 9.1.0 (clang-902.0.39.1)
Target: x86_64-apple-darwin17.5.0
Thread model: posix

Upvotes: 0

Views: 5042

Answers (3)

Thomas Matthews
Thomas Matthews

Reputation: 57678

I recommend not placing data into a header file.
Any source file including the header will get a copy of the data.

Instead, use an extern declaration:

data.h:

extern char const * data[3];

data.cpp:

char const * data[3] = {"asdf","qwer","hjkl"};

Upvotes: 2

AnT stands with Russia
AnT stands with Russia

Reputation: 320381

The need to provide a separate out-of-line definition (with an initializer) for static class members is rooted in the fact that the exact point of definition in C++ affects the order of initialization and location of the exported symbol in object files. The language wants you to make these decisions yourself.

However, to simplify things in those frequent cases when you don't care about such stuff, starting from C++17 you can do exactly what you want by specifying an explicit inline keyword in static member declaration

class test{
  static inline const char* const ar[] = { "asdf", "qwer", "hjkl" };
};

Upvotes: 5

realtimeguy
realtimeguy

Reputation: 1

This worked even if I put all of it into the header file (in which case however, line_001 has to be after the class definition block, just as shown below). But you can also put the line_001 into the cpp file.

With the const pointer:

class MyClass
{
public:
    MyClass();
    static char const* const arr[3];
};



char const* const MyClass::arr[3] = {"aaaa", "bbbbb", "ccccc"};

Without the const pointer:

class MyClass
{
public:
    static const char* arr[3];
};

const char* MyClass::arr[3] = {"aaaa", "bbbbb", "ccccc"}; // line_001

Upvotes: 0

Related Questions