In C++ (overload resolution with default parameters), what does the following program print? Focus on which Addition overload is selected in each call. #include<iostream.h> struct MyData { public: int Addition(int a, int b = 10) { return (a *= b + 2); } float Addition(int a, float b); }; int main() { MyData data; cout << data.Addition(1) << " "; cout << data.Addition(3, 4); return 0; }

Difficulty: Medium

Correct Answer: 12 18

Explanation:


Introduction / Context:
Overload resolution in C++ prefers the best match. Here one overload is int Addition(int,int) with a default second parameter, and the other is float Addition(int,float) (declared but not defined). Understanding which is chosen in each call determines the output values and whether the code links successfully.


Given Data / Assumptions:

  • data.Addition(1) supplies a single int argument.
  • data.Addition(3, 4) supplies two int arguments.
  • The float overload is declared but never used by the calls as written.


Concept / Approach:
For Addition(1), the viable candidate is int,int with default b=10. For Addition(3,4), the exact match is also int,int. Both calls therefore select the same overload that returns int. The computation in that overload is a *= (b + 2) which means a = a * (b + 2) and returns the updated a.


Step-by-Step Solution:

First call: a=1, b=10 → a = 1 * (10 + 2) = 12 Second call: a=3, b=4 → a = 3 * (4 + 2) = 18 Output: "12 18"


Verification / Alternative check:
If the second call had a float as the second argument (e.g., 4.0f), the float overload would be selected and would require a definition to link. As written, no link error occurs because that overload is never used.


Why Other Options Are Wrong:

  • 12 12, 3 14, 18 12: Mismatch the arithmetic with supplied parameters.
  • Compilation fails: Not for the provided calls.


Common Pitfalls:
Assuming the mere presence of an undefined overload triggers a link error even if it is not selected by any call site.


Final Answer:
12 18

More Questions from Functions

Discussion & Comments

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