Can I use default arguments in a constructor like this maybe
Soldier(int entyID, int hlth = 100, int exp = 10, string nme) : entityID(entyID = globalID++), health(hlth), experience(exp), name(nme = SelectRandomName(exp))
{ }
I want for example exp = 10 by default but be able to override this value if I supply it in the constructor otherwise it should use the default.
How can I do this, I know my approach does not work....
If I supply any value in the initialization list no matter whatever I supply in constructor gets overwritten ofcourse on the other hand whenever I supply a value in constructor then why do I need a default value in the first place as every time I am supplying a value for object initiation...?
Should I use different overloaded constructors or do you people have any other ideas....?
Arguments with default values must be the last arguments in the function declaration. In other words, there can not be any arguments without default values following one with a default value.
Default arguments can only be supplied to a continuous range of parameters that extends to the end of the parameter list. Simply speaking, you can supply default arguments to 1, 2, 3, ... N last parameters of a function. You cannot supply default arguments to parameters in the middle of the parameter list, as you are trying to do above. Either rearrange your parameters (put
hlth
andexp
at the end) or supply a default argument fornme
as well.Additionally, you constructor initializer list doesn't seem to make any sense. What was the point of passing
entyID
andnme
from outside, if you override their values anyway in the constructor initializer list?I believe you can do this, however, all your defaulted args would need to go at the end. So, in your example, the constructor signature would be
Only trailing arguments can be default arguments. You would need to give
nme
a default argument or change the order of the arguments that the constructor takes so thathlth
andexp
come last.As regards the assignment you make in the initialiser list what happens there is that the member
entityID
gets assigned the value that is returned by the assignment ofglobalID++
toentyID
which will be the value ofentyID
after the assignment. A similar thing happens forname
.All of the parameters with default arguments need to be after any required arguments. You should move the
nme
parameter beforehlth
.