4

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?

0

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

The drawback to this is if N is large, as you then have to write quite a long initializer list.
3

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

1 Comment

This look like a better answer. It uses R to initialize myA.

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.