Self-test 8:
Function overloading, default arguments, etc.

  1. What is the expected result during the development and/or execution of the following code?

    #include <iostream>
    using namespace std;
    
    void func(int a)
    {
        cout << a << endl;  
    }
    
    void func(int a, int& b)
    {
        cout << a << " " << b << endl;
    }
    
    int main()
    {
        func(10,20);
        func(5) ;
        return 0 ;
    }
    
    1. No matched function is found, resulting in a compilation error
    2. 10 20
      5
    3. Run time error
    4. 5 (only because func(int a, int& b) is not called)
    5. the formal parameter, int& b, accepts only a variable argument. Thus, there will be compilation error.
    Solution

    A.
    The answer is A because the function call, func(10,20), should be matched by a function with the prototype func(int,int); after possible parameter coercion. But only func(int) and func(int, int&) are available. E will not be considered because we there are overloaded functions in this example. If func is not overloaded and only void func(int, int&) exists, there the answer will be E.


  2. What is the expected result during the development and/or execution of the following code?

    void func(int a = 100, int b = 200, int c = 200)
    {
        cout << (a + b + c);
    }
    
    void func(int a, int b, int c)
    {
        cout << (a + b + c);
    }
    
    int main()
    {
        func(1,10,100);
        func();
        return 0 ;
    }
    
    1. No matched function is found, resulting in a compilation error
    2. 111 500
    3. Run time error
    4. 500 500
    5. Re-definition of the same function
    Solution

    E.
    It is not allowed to have 2 definitions of func that have the same signature. The use of default arguments in the first definition does not change the fact that the signatures of the 2 definitions are the same, causing ambiguity in calling the function func.