C++ vector as class member vs in function

Viewed 49

When I am using vector as following in a function, I get a variable D and it works.

 vector<int> D(100);

However, when I decide to use this as a class member, I get the following weird error :

error: expected identifier before numeric constant
   99 |     vector<int> D(100);
      |                   ^~~

Could someone explain why this particular error ? I can use array in a class as int D[100].

1 Answers

Default member initializer (since C++11) for member variable only supports equal-sign initializer (and braced-initializer, which doesn't match this use-case).

Through a default member initializer, which is a brace or equals initializer included in the member declaration and is used if the member is omitted from the member initializer list of a constructor.

You can

vector<int> D = vector<int>(100);

Or use member intializer list. e.g.

struct x {
    vector<int> D;
    x() : D(100) {}
};
Related