Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default object values in functions with default argument values

Tags:

c++

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

like image 923
stiv.r Avatar asked Jun 18 '13 08:06

stiv.r


People also ask

How do default values relate to arguments in a function?

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.

Can you assign the default values to a function parameters?

Default function parameters allow named parameters to be initialized with default values if no value or undefined is passed.

How can we use default arguments in the function?

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.

When can any argument have a default value?

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.


1 Answers

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));
like image 114
juanchopanza Avatar answered Sep 27 '22 22:09

juanchopanza