Reputation: 1863
I've just seen this syntax for a function prototype in C++:
explicit String(unsigned char value, unsigned char base=10);
I haven't seen this before, but am I right in assuming it sets base
to 10 regardless of what you call it with?
Upvotes: 5
Views: 751
Reputation: 95998
See this link:
When declaring a function we can specify a default value for each of the last parameters. This value will be used if the corresponding argument is left blank when calling to the function. To do that, we simply have to use the assignment operator and a value for the arguments in the function declaration. If a value for that parameter is not passed when the function is called, the default value is used, but if a value is specified this default value is ignored and the passed value is used instead.
The explicit keyword prevents implicit conversions:
C++ ctors (constructors) that have just one parameter automatically perform implicit type conversion. For example, if you pass an int when the ctor expects a string pointer parameter, the compiler adds the code it must have to convert the int to a string pointer. However, this automatic behavior can cause errors.
Upvotes: 0
Reputation: 8975
base
has a default value. You can assign a default value for every parameter, given that all following parameters have default values as well.
explicit
prevents implicit conversions, so String k = 0
will not be accepted as valid - it would call String(0, 10)
otherwise.
Upvotes: 1
Reputation: 19272
The default parameter, called base
will take whatever value you send it, or the value 10, if you leave it off, e.g. by calling
String(0);
Given that you can call it with just one parameter, since the second can be defaulted, a constructor can be marked as explicit
. This means it won't create a temporary from an unsigned char
without you noticing, you have to explicitly call the constructor.
Upvotes: 4