So far I know that if you want to pass a default value for an argument to a function that is an object, you do it like this:
void function(MyObject obj = MyObject()){
...
}
However, I've come around to some interesting syntax lately, which confuses me. What happens when we call the function like this?
void function(MyObject obj = 0){
...
}
Note, we are passing an object, not a pointer. The above code compiles just fine, no errors or warnings. And this always calls the constructor with one argument - MyObject is defined like this:
class MyObject{
public:
MyObject(double n){std::cout << "Argumented\n";}
MyObject(){std::cout << "Default\n";}
};
Also, where is this behavior documented (because I searched and couldn't find it)?
Once a default value is used for an argument in the function definition, all subsequent arguments to it must have a default value as well. It can also be stated that the default arguments are assigned from right to left.
Default function parameters allow named parameters to be initialized with default values if no value or undefined is passed.
If a function with default arguments is called without passing arguments, then the default parameters are used. However, if arguments are passed while calling the function, the default arguments are ignored.
Of the operators, only the function call operator and the operator new can have default arguments when they are overloaded. You can supply any default argument values in the function declaration or in the definition.
The pararameter defaults to a MyObject
implicitly constructed from 0
, by calling the MyObject(double)
constructor. This constructor allows you to implicitly instantiate MyObjects
like this:
MyObject o1 = 0;
MyObject o2 = 420/10.;
If this behaviour is not intended, then make the constructor explicit
. This will also require a change to function
's default parameter:
explicit MyObject(double n);
and
void function(MyObject obj = MyObject(0));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With