Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 506
Spyridon Non Serviam Avatar asked Feb 14 '23 15:02

Spyridon Non Serviam


2 Answers

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.

like image 196
Sam Cristall Avatar answered May 18 '23 12:05

Sam Cristall


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).

like image 35
Some programmer dude Avatar answered May 18 '23 14:05

Some programmer dude