Default arguments in constructor
Can I use default arguments in a constructor like this, perhaps
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, the default exp = 10, but I can override this value if I put it in the constructor, otherwise it must use the default.
How can I do this, I know my approach is not working ...
If I put any value in the initialization list, no matter what I put in the constructor, on the other hand, is overwritten, if I put a value in the constructor, then why do I need the default value in the first place, since every time I supply values to initiate an object ...?
Should I use different overloaded constructors or do you have any other ideas ...?
source to share
Default arguments can only be provided for a contiguous range of parameters that continues to the end of the parameter list. Simply put, you can provide default arguments for the 1, 2, 3, ... N last parameters of the function. You cannot provide default arguments for parameters in the middle of the parameter list as you are trying to do above. Either change the options (put hlth
and exp
at the end) or provide a default argument for nme
.
Also, the list of constructor initializers doesn't seem to make any sense. What was the point of passing in entyID
and out nme
from outside, if you override their values in the constructor's initializer list anyway?
source to share
Only trailing arguments can be used as default arguments. You need to provide a nme
default argument or change the order of the arguments that the constructor takes to be hlth
and exp
.
As for the assignment you make in the initialization list, what happens is that the member entityID
gets the value returned by the assignment globalID++
- entyID
which will be the value entyID
after assignment. A similar situation takes place for name
.
source to share