0

I want to write a code in c++ so that the I can initialize a class using a constructor with unknown number of parameters. I have an array in my class and i want to store all the values that i pass to my constructor to be stored in the array. Is it possible to do so.

  • 2
    Why not simply have an array (or vector) as a constructor parameter? – Yuushi Oct 23 '12 at 03:37
  • What compiler and version are you using? This is possible in two ways with C++11. Either variadic templates, or initializer lists. – Benjamin Lindley Oct 23 '12 at 03:38
  • For an array as the parameter, http://liveworkspace.org/code/7823999f46ff0a4fa45674f695b3f9ab. A vector or something would be better if you have C++11. – chris Oct 23 '12 at 03:38
  • Possible dupe: http://stackoverflow.com/questions/6179812 – Dan Oct 23 '12 at 03:39
  • I compile on ideone which uses C++ (gcc-4.3.4). – illumiNatISt Oct 23 '12 at 03:42
  • That's a bit odd. If, for whatever reason, you are forced to use an online compiler, here's one that uses gcc 4.7, and it includes an up to date version of boost: http://liveworkspace.org/ – Benjamin Lindley Oct 23 '12 at 03:49

1 Answers1

2

The best approach in C++11 would be to have a construcor that takes a std::initializer_list<T> where T is the type stored in the array.

Other options include taking a pointer to a different array, or a std::vector<T> (BTW, consider using std::vector rather than a plain array).

David Rodríguez - dribeas
  • 204,818
  • 23
  • 294
  • 489