C++ Default values in functions?

3.5k views Asked by At

How exactly do default values in functions work? My question pertains to this example:

int func(int number, std::string name = "None", int anotherNumber);

..

int func(int number, std::string name, int anotherNumber){
    ...
}

func(1, 2);
^Error, name is NULL yet we've defined a default value?

The compiler gives an error complaining that the argument was NULL and should not be. Yet I've defined a default value for it.

Why is this?

2

There are 2 answers

0
Acha Bill On

Default arguments are last.

int func(int number1, int number2, std::string = "none");
...
func(1,2); 

https://en.wikipedia.org/wiki/Default_argument

5
Sergey Kalinichenko On

If a default parameter at position k is supplied, all parameters in positions from k+1 to the end must be supplied as well. C++ allows you to omit parameters only in the end positions, because otherwise it has no way of matching parameter expressions to formal parameters.

Consider this example:

int func(int a, int b=2, int c, int d=4);
...
foo(10, 20, 30);

This call is ambiguous, because it supplies three parameters out of four. If declaration above were allowed, C++ would have a choice of calling

func(10, 20, 30, 4);

or

func(10, 2, 30, 40);

With all defaulted parameters at the end and a rule that parameters are matched by position, there would be no such ambiguity:

int func(int a, int b, int c=2, int d=4);
...
foo(10, 20, 30); // means foo(10, 20, 30, 4);