Reputation: 1284
How do I make a dynamic constructor which takes in x amount of parameters, in c++?
For example:
my_constructor(int,int,...);
there can be as many ints as the user inputs.
Is this even possible?
Upvotes: 0
Views: 64
Reputation: 4236
The way you're talking about it, I don't think it would be possible. How would you assign all those arguments to fields? You'd need to dynamically generate different fields for the object! I'm almost certain that's not possible. What you can do instead, however, is make the constructor take an array as part of its arguments, which you can fill with a varying number of 'sub-arguments'. Good luck.
Upvotes: 0
Reputation: 26080
If they're all arguments of the same type, simply use an initializer list.
struct foo
{
foo(std::initializer_list<int> init)
{
....
}
}
You'd still need to add these to a container of some kind, however (for example):
struct foo
{
std::vector<int> v;
foo(std::initializer_list<int> init)
: v(init.begin(), init.end())
{ }
};
Upvotes: 2