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.

6
  • 2
    Why not simply have an array (or vector) as a constructor parameter? Commented Oct 23, 2012 at 3:37
  • What compiler and version are you using? This is possible in two ways with C++11. Either variadic templates, or initializer lists. Commented Oct 23, 2012 at 3:38
  • For an array as the parameter, liveworkspace.org/code/7823999f46ff0a4fa45674f695b3f9ab. A vector or something would be better if you have C++11. Commented Oct 23, 2012 at 3:38
  • Possible dupe: stackoverflow.com/questions/6179812 Commented Oct 23, 2012 at 3:39
  • I compile on ideone which uses C++ (gcc-4.3.4). Commented Oct 23, 2012 at 3:42

1 Answer 1

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

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

Comments

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.