Spyridon Non Serviam
Spyridon Non Serviam

Reputation: 387

Initialization list for an array of objects that that take parameters C++

In C++ I am trying to initialize in my constructor an array of objects that their constructor takes one or more arguments. I want to do this on the initialization list of the constructor and not its body. Is this possible and how?

What I mean:

class A{
  public:
    A(int a){do something};
}

class B{
  private:
    A myA[N];
  public:
    B(int R): ???? {do something};
}

What should I put in the ??? to initialize the array myA with a parameter R?

Upvotes: 4

Views: 3359

Answers (2)

Sam Cristall
Sam Cristall

Reputation: 4387

If you have C++11, you can do:

B(int R) : myA{1, 2, 3, 4, 5, 6} { /* do something */ }

Although, if you are using Visual Studio 2013, please note that this syntax is currently NOT supported. There is the following workaround, however (which is arguably better style anyways):

#include <array>

class B {
    std::array<A, N> myA;

public:
    B(int R) : myA({1, 2, 3, 4, 5, 6}) {}
};

Note, however, that N has to be a compile-time constant, and the number of initializers has to match the number of initializers.

Upvotes: 6

Some programmer dude
Some programmer dude

Reputation: 409196

In this case it might be simpler to use a std::vector:

class B
{
    std::vector<A> myA;

public:
    B(int R) : myA(N, A(R)) {}
};

The constructor initializer constructs the vector with N entries all initialized to A(R).

Upvotes: 3

Related Questions