How do you declare arrays in a c++ header?


Question

This is related to some other questions, such as: this, and some of my other questions.

In this question, and others, we see we can declare and initialise string arrays in one nice step, for example:

const char* const list[] = {"zip", "zam", "bam"}; //from other question

This can be done in the implementation of a function with no bother, or in the body of a .cpp file, outside any scope.

What I want to do is to have an array like this as as member of a class I am using, something like this:

class DataProvider : public SomethingElse
{
    const char* const mStringData[] = {"Name1", "Name2", "Name3", ... "NameX"};

public:
    DataProvider();
    ~DataProvider();

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

};

But, the compiler complains and I can't seem to work out why. Is it possible to declare and initialise an array like this in one step in a class definition? Are there alternatives that are better?

1
22
7/6/2019 12:05:43 AM

Accepted Answer

Use the keyword static and external initialization to make the array a static member of the 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"};
18
11/12/2008 6:44:37 PM

The reason you can't declare your array 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 probably want to make that array static, since it is in essence a constant value.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon