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?
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.
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)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With