3

Usually when writing a constructor I try to initialize as many class members as possible in the member initialization list, including containers such as std::vector.

class MyClass
{
  protected:
  std::vector<int> myvector;

  public:
  MyClass() : myvector(500, -1) {}
}

For technical reasons, I now need to split this into an array of vectors.

class MyClass
{
  protected:
  std::vector<int> myvector[3];

  public:
  MyClass() : myvector[0](500, -1), myvector[1](250, -1), myvector[2](250, -1) {}
}

Turns out, I cannot initialize the array of vectors this way. What am I doing wrong? Or is this just not possible?

Of course I can still do this in the body of the ctor using assign, but I'd prefer to do it in the member init list.

JFMR
  • 23,265
  • 4
  • 52
  • 76
marcbf
  • 139
  • 1
  • 2
  • 10

1 Answers1

3

You should initialize the whole array, but not every element. The correct syntax to initialize the array should be

MyClass() : myvector {std::vector<int>(500, -1), std::vector<int>(250, -1), std::vector<int>(250, -1)} {}
songyuanyao
  • 169,198
  • 16
  • 310
  • 405
  • Hmm... I get the following error `Error C2536: cannot specify explicit initializer for arrays`. This is MSVC2013 by the way. As for the contents of the vectors, the first one should be initialized with 500 entries of -1, while the last two each should be initialized with 250 entries of -1. – marcbf Dec 07 '17 at 08:22
  • @azrael I tried it [here](http://rextester.com/OKJCI47855) and it compiles; I'm not sure, might be VS2013's bug. – songyuanyao Dec 07 '17 at 08:25
  • @azrael Does the normal array initializatioin for local variable work? like `std::vector myvector[3] { std::vector(500, -1), std::vector(250, -1), std::vector(250, -1)};` – songyuanyao Dec 07 '17 at 08:28
  • Just looked up the error: https://msdn.microsoft.com/query/dev12.query?appId=Dev12IDEF1&l=EN-US&k=k(C2536);k(VS.ErrorList);k(DevLang-C%2B%2B)&rd=true Seems to be a shortcoming of MSVC2013 and earlier, since there's no related entry for MSVC2015 and newer. – marcbf Dec 07 '17 at 08:40
  • @azrael Try surrounding the *curly braces* between *parenthesis* as in `MyClass() : myvector({std::vector(500, -1), std::vector(250, -1), std::vector(250, -1)}) {}` – JFMR Dec 07 '17 at 08:45
  • @azrael Maybe you need an extra pair of curly braces, see: https://stackoverflow.com/questions/19877757/workaround-for-error-c2536-cannot-specify-explicit-initializer-for-arrays-in-vi – JFMR Dec 07 '17 at 08:47
  • Seems to be another shortcoming of MSVC2013 (and 2015). https://msdn.microsoft.com/query/dev12.query?appId=Dev12IDEF1&l=EN-US&k=k(C2797);k(VS.ErrorList);k(register_CPP);k(register);k(DevLang-C%2B%2B);k(TargetOS-Windows)&rd=true – marcbf Dec 07 '17 at 09:19
  • 1
    Accepting the answer, since this is the proper way, even if I can't get it to work. – marcbf Dec 08 '17 at 08:36