Search code examples
c++overloadingdefault-value

What does the C++ compiler do when coming ambiguous default parameters?


What does the C++ compiler do when coming ambiguous default parameters? For example, let's say there was a function such as:

void function(int a = 0, float b = 3.1);
void function(int a, float b =1.1, int c = 0);

Is the above considered ambiguous? If not, what does the compiler do (how is the function matched exactly) when calling something like function1(10) ?

Thanks!


Solution

  • The following is fine

    void function(int a = 0, float b = 3.1);
    void function(int a, float b =1.1, int c = 0);
    

    And the following is fine too

    function(); // calls first function
    

    But the following is ambiguous

    function(1); // second and first match equally well
    

    For overload resolution (the process that tells what function to call), parameters that have not passed explicit arguments and that make use of default arguments are ignored. So the compiler really sees two functions both having one int parameter for the above call and can't decide.

    The following is ill-formed though

    void function(int a = 0, float b = 3.1);
    void function(int a, float b =1.1);
    

    While for the code in your question you declare two functions (because both declarations have different number of parameters), in this example you only declare one function. But the second declaration of it repeats a default argument for a parameter (and even with a different value, but that doesn't matter anymore). This is not allowed. Note that the following is fine

    void function(int a, float b = 3.1);
    void function(int a = 0, float b);
    

    The set of default arguments for declarations that appear in the same scope for the same function are merged, and only for those that appear in the same scope. So the following is valid

    void function(int a = 0, float b = 3.1);
    void function1() {
      void function(int a, float b = 1.1); 
      function(0);
    }
    

    This calls the function with 1.1 passed for b.