Zining Zhu
Zining Zhu

Reputation: 323

Initializing string array in a class function

I tried to initialize an array of string in class as following:

class Haab{
    string str[];
    Haab(){
        str[] = {"abc", "abd", "abe"};
    }
};

But the Devc++ 5.6.1 reports a warning:

[Warning] extended initializer lists only available with -std=c++11 or -std=gnu++11 [enabled by default]

Is this way of initializing arrays in class illegal? If so, how to properly initialize the array? Thank you.

Upvotes: 1

Views: 272

Answers (1)

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145279

The given code,

class Haab{
    string str[];
    Haab(){
        str[] = {"abc", "abd", "abe"};
    }
};

is invalid in a number of ways:

  • string str[]; declares a member array of unknown size. Can't do that.

  • In str[] = {"abc", "abd", "abe"};, the expression str[] uses the [] indexing operator without specifying the index.

  • If that parsed, then the = would denote assignment of a single string.

Here's one C++03 way to do things:

#include <string>
#include <vector>

namespace qwe {
    using std::string;
    using std::vector;

    class Haab
    {
    private:
        vector<string> str_;

    public:
        Haab()
        {
            static char const* const data[] = {"abc", "abd", "abe"};

            for( int i = 0; i < 3; ++i )
            {
                str_.push_back( data[i] );
            }
        }
    };
}  // namespace qwe

There are also other C++03 ways, all of them ugly (as the above).

In C++11 and later it can be done with more elegant & simple notation;

#include <string>
#include <vector>

namespace qwe {
    using std::string;
    using std::vector;

    class Haab
    {
    private:
        vector<string> str_;

    public:
        Haab()
            : str_{ "abc", "abd", "abe"}
        {}
    };
}  // namespace qwe

but this does still not compile with Visual C++ 13.0 (it does compile with MinGW g++ 4.9.1).

Upvotes: 2

Related Questions