I have to write constructor with two default parameters.
func(int arg1 , char* arg2 = "arg2", int arg3 = 1) //example
I am provided the scenario where the constructor is called and a value is given to arg1
and arg2
and arg3
is expected to use a default value. Then another object is instantiated and a value is given to arg1
and arg3
, and default value for arg2
is expected to be used.
Now the problem is, you "can't skip" default parameters is what I'm reading from the text and online. It's saying to order the default paramters from its likliness of being overloaded, but the scenario has one default parameter used while the other isn't. The hints for this question tells me to reorder the parameters/arguments. However, no amount of reordering that I've done seem to be able to resolve this issue.
Also, overloaded constructors can not be used. This has to be done by one constructor.
So how would one do this? I'm stumped and going a bit crazy over this :(
Right now you can use std::bind to do this kind of operation or in c++14/17 you can use lambda function and accomplish the same.
Peculiar restriction, that there must be only one constructor. Here's the closest I can think of:
Note that with GCC this generates warnings, since the conversion from a string literal to non-const
char*
is deprecated and unwise. But it's what you asked for, and fixing it so that thechar*
parameters and data member areconst char*
is easy enough.A significant weakness is that this doesn't stop you writing
Foo(1,2,3)
. To check that at compile-time I think you need multiple constructors. To check it at runtime, you could make the third parameter into another class,DefaultOrInt
, whereDefault
is a type used just for this purpose, supporting only one value used as the default value ofarg3
. Then ifarg2.isInt()
is true, checkarg3.isInt()
is false and if not throwlogic_error
.The only reason I can think of for this requirement is that the optional arguments have the same type. In that case, you're stuck and you'll want to look into the named constructor and/or named parameter idioms.
Otherwise, just define the extra constructor. This may involve some duplication wrt. the default values.
If you're allowed to pass an empty C-string when you've got no value for the second parameter, you could use a helper functor that'll check
arg2
and return default value if it's empty. Something like this:Not pretty, I know...