[ACCEPTED]-How do you declare arrays in a c++ header?-constants

Accepted answer
Score: 18

Use the keyword static and external initialization 2 to make the array a static member of the 1 class:

In the header file:

class DataProvider : public SomethingElse
{
    static const char* const mStringData[];

public:
    DataProvider();
    ~DataProvider();

    const char* const GetData()
    {
        int index = GetCurrentIndex(); //work out the index based on some other data
        return mStringData[index]; //error checking and what have you omitted
    }

};

In the .cpp file:

const char* const DataProvider::mStringData[] = {"Name1", "Name2", "Name3", ... "NameX"};
Score: 3

This is not possible in C++. You cannot 14 directly initialize the array. Instead you 13 have to give it the size it will have (4 12 in your case), and you have to initialize 11 the array in the constructor of DataProvider:

class DataProvider {
    enum { SIZEOF_VALUES = 4 };
    const char * values[SIZEOF_VALUES];

    public:
    DataProvider() {
        const char * const v[SIZEOF_VALUES] = { 
            "one", "two", "three", "four" 
        };
        std::copy(v, v + SIZEOF_VALUES, values);
    }
};

Note 10 that you have to give up on the const-ness 9 of the pointers in the array, since you 8 cannot directly initialize the array. But 7 you need to later set the pointers to the 6 right values, and thus the pointers need 5 to be modifiable.

If your values in the 4 array are const nevertheless, the only way 3 is to use a static array:

/* in the header file */
class DataProvider {
    enum { SIZEOF_VALUES = 4 };
    static const char * const values[SIZEOF_VALUES];
};

/* in cpp file: */

const char * const DataProvider::values[SIZEOF_VALUES] = 
    { "one", "two", "three", "four" };

Having the static 2 array means all objects will share that 1 array. Thus you will have saved memory too.

Score: 3

The reason you can't declare your array 3 like that (const char* []) is that:

  • you can't have initializers in the class declaration, and so
  • the syntax const char* [] does not state how much space the compiler needs to allocate for each instance (your array is declared as instance variable).

Besides, you 2 probably want to make that array static, since 1 it is in essence a constant value.

More Related questions