C++ – Initialize Static Const Array of Const Strings

c++compiler-errorsconstantsinitialization

I am having trouble initializing a constant array of constant strings.

From week.h (showing only relevant parts):

class Week {
  private:
    static const char *const *days = { "mon", "tue", "wed", "thur",
                                       "fri", "sat", "sun" };
};

When I compile I get the error "excess elements in scalar initializer". I tried making it type const char **, thinking I messed up the 2nd const placement, but I got the same error. What am I doing wrong?

Best Answer

First of all, you need an array, not a pointer.

static const char * const days[] = {"mon", "tue", "wed", "thur",
                                       "fri", "sat", "sun"};

Second of all, you can't initialize that directly inside the class definition. Inside the class definition, leave only this:

static const char * const days[]; //declaration

Then, in the .cpp file, write the definition

const char * const Week::days[] = {"mon", "tue", "wed", "thur",
                                       "fri", "sat", "sun"};

Update for C++11 Now you can initialize members directly in the class definition:

const char * const days[] = {"mon", "tue", "wed", "thur",
                                       "fri", "sat", "sun"};
Related Question