1

I have a situation where I need to create instances of a class with many object pointer parameters. But, I'm looking for a simpler way. In this code sample, I demonstrate very generically what I'm trying to do.

#include <vector>
#include <string>
class A
{
  public:
    A(std::string param);
};
class B
{
  public:
    B(std::vector<A*> params);
};
int main(int argc, char* argv[])
{
  std::vector<A*> my_arguments;
  my_arguments.push_back(new A("A1"));
  my_arguments.push_back(new A("A2"));
  my_arguments.push_back(new A("A3"));
  my_arguments.push_back(new A("A4"));

  B my_b = new B(my_arguments);
}

I don't like having to use an additional 5 lines to create the parameters for this call. Is there an alternate way to do this that requires less code. I tried using an array like so, but it doesn't seem to be working:

  B my_b = new B([new A("A1"), new A("A2"), new A("A3"), new A("A4")]);

How could I achieve a similar result? I thought about using va_list, but that would require another parameter marking the end, or a count of the number of variables. It might be what I end up doing, but, are there any other strategies out there?

Richard Chambers
  • 16,643
  • 4
  • 81
  • 106
  • Nit: don't use `new`, use `std::make_unique/std::unique_ptr<>`. – GManNickG Oct 05 '15 at 03:44
  • 1
    Possible duplicate of [What is the easiest way to initialize a std::vector with hardcoded elements?](http://stackoverflow.com/questions/2236197/what-is-the-easiest-way-to-initialize-a-stdvector-with-hardcoded-elements) – Michael Albers Oct 05 '15 at 03:44
  • 1
    @MichaelAlbers, not really a duplicate since the one you reference is using POD `int` while this is a `vector` of pointers. Not sure you could get from any of the answers to that question to an answer for this one especially with those being old. – Richard Chambers Oct 05 '15 at 04:33

1 Answers1

1

You were nearly there...

B my_b{{new A("A1"), new A("A2"), new A("A3"), new A("A4")}};

Note: your code was trying to create B my_b which is not a pointer, so you don't need to use new. The outer { } pair surround the argument to the constructor, the inner { } pair create a std::initializer_list for the std::vector constructor, so the values therein are used to construct the std::vector argument.

Note that this syntax has been supported since C++11 - some compilers needs command line arguments to enable support for the C++11 Standard, e.g. gcc -std=c++11 ....

Tony Delroy
  • 102,968
  • 15
  • 177
  • 252