Is there a less code dense way to initialise an array with a non default constructor?

Viewed 75

I have an array of 4 objects, each of these objects are initialised with a non default constructor however the same variables are used for all 4 with no changes required. This code works, however I would like to know if there is a less code dense way of initialising each object as each of the array elements are just being initialised with the same values?

Class1.h:
std::array<Arrow, 4> skillArrow

Class1.cpp:
Class1::Class1() : skillArrow{ Arrow("gfx/leftArrow.png", mouse, input), Arrow("gfx/leftArrow.png", mouse, input), Arrow("gfx/leftArrow.png", mouse, input), Arrow("gfx/leftArrow.png", mouse, input)
{
}
Arrow.h:
Arrow(const char* filePath, Sprite *mouseSprite, Input *input);

2 Answers

You can use a delegating constructor like this:

struct Class1 {
 private:
  std::array<Arrow, 4> skillArrow;

  Class1(Arrow const & arrow) : skillArrow{arrow, arrow, arrow, arrow} {}

 public:
  Class1();
};

Class1::Class1() : Class1(Arrow("gfx/leftArrow.png", mouse, input)) {}

You could use std::array<T,N>::fill in the constructor.

Class1::Class1() {
    skillArrow.fill({"gfx/leftArrow.png", mouse, input});
}

If, as Nate Eldredge pointed out, is important to call the Arrow constructor four times, a normal loop would do the trick.

Class1::Class1() {
    for ( auto & s : skillArrow )
        s = Arrow("gfx/leftArrow.png", mouse, input);
}
Related