Self-test 8:
Function overloading, default arguments, etc.
-
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 ; }- No matched function is found, resulting in a compilation error
- 10 20
5 - Run time error
- 5 (only because func(int a, int& b) is not called)
- the formal parameter, int& b, accepts only a variable argument. Thus, there will be compilation error.
SolutionA.
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.
-
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 ; }- No matched function is found, resulting in a compilation error
- 111 500
- Run time error
- 500 500
- Re-definition of the same function
SolutionE.
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.