user1701545
user1701545

Reputation: 6190

C++ error: a brace-enclosed initializer is not allowed here before ‘{’ token

Simple question:

I'm trying to initialize an array within a C++ class declaration:

using namespace std;
#include <string>
class myClass{
public:
  string myArray[] = {"a","b","c"};
};

and I'm getting the error:

error: a brace-enclosed initializer is not allowed here before ‘{’ token

Upvotes: 3

Views: 7513

Answers (2)

simon
simon

Reputation: 391

No, without a complied C++11 compiler, you cannot initialize a member array in its declaration. You have to initialize array member in your constructor. And don't use open array if you know the number of elements to initialize the array.

Upvotes: 3

Brian Bi
Brian Bi

Reputation: 119069

The real problem is simply that a non-static array data member may not be declared without a bound. At block scope or namespace scope the initializer will be used to deduce the size, but not at class scope. So just change this to:

string myArray[3] = {"a","b","c"};

and it should be fine.

Upvotes: -1

Related Questions