4

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.

1 Answer 1

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)} {}
Sign up to request clarification or add additional context in comments.

8 Comments

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.
@azrael I tried it here and it compiles; I'm not sure, might be VS2013's bug.
@azrael Does the normal array initializatioin for local variable work? like std::vector<int> myvector[3] { std::vector<int>(500, -1), std::vector<int>(250, -1), std::vector<int>(250, -1)};
Just looked up the error: msdn.microsoft.com/query/… Seems to be a shortcoming of MSVC2013 and earlier, since there's no related entry for MSVC2015 and newer.
Accepting the answer, since this is the proper way, even if I can't get it to work.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.