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

+2


source to share


5 answers


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?

+8


source


All parameters with default arguments must come after any required arguments. You must move the parameter nme

to hlth

.



+2


source


I believe you can do this, however all your default arguments will have to go at the end. So in your example, the signature of the constructor would be

Soldier(int entyID, string nme, int hlth = 100, int exp = 10);

      

+2


source


Arguments with default values ​​must be the last arguments in the function declaration. In other words, there can be no arguments without default values ​​following a default value.

+1


source


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

.

+1


source







All Articles