C++ overloading with a competing overload that has a default argument: which function is called and what is printed? #include int CuriousTabTest(int x, int y); int CuriousTabTest(int x, int y, int z = 5); int main() { cout << CuriousTabTest(2, 4) << endl; return 0; } int CuriousTabTest(int x, int y) { return x * y; } int CuriousTabTest(int x, int y, int z /= 5/) { return x * y * z; }

C++ Programming Functions Difficulty: Medium
Choose an option
  • A
    The program will print the output 5.
  • B
    The program will print the output 8.
  • C
    The program will print the output 40.
  • D
    The program will report compile time error.
  • E
    None of the above

Answer

Correct Answer: The program will print the output 8.

Explanation

Introduction / Context: This item examines overload resolution when one overload exactly matches the argument list and another is also viable by supplying a default argument. The C++ rules select the best viable function, favoring an exact arity match over one that relies on defaults.

Given Data / Assumptions:

  • Two overloads exist: f(int,int) and f(int,int,int=5).
  • Call site: CuriousTabTest(2, 4).
  • Both overloads are viable, but one requires using a default argument for the third parameter.

Concept / Approach: Overload resolution prefers the function that requires no default arguments and exactly matches the number and types of the provided parameters. Therefore CuriousTabTest(int,int) is selected, computing 2 * 4 = 8.

Step-by-Step Solution:

Evaluate candidates: (int,int) and (int,int,int=5).Both match types; the three-parameter overload needs its default for z.Best viable function is the exact two-parameter overload.Return 2 * 4 → 8; cout prints 8.

Verification / Alternative check: If the call were CuriousTabTest(2,4,5), the three-parameter version would be chosen and print 40. Removing the two-parameter overload would also yield 40 due to the default.

Why Other Options Are Wrong:

  • 5: Not computed by either overload.
  • 40: Would require calling the three-parameter function explicitly (or removing the two-parameter overload).
  • Compile time error / None of the above: The overload set is resolvable.

Common Pitfalls: Thinking the presence of a defaulted parameter forces selection of that overload; in reality, defaults only make a function viable, not necessarily the best match.

Final Answer: The program will print the output 8.

Discussion & Comments
No comments yet. Be the first to comment!
Join Discussion