C++ overload resolution on integral and floating return types: which overload is called and what is printed?\n\n#include<iostream.h>\nlong GetNumber(long int Number)\n{\n return --Number;\n}\nfloat GetNumber(int Number)\n{\n return ++Number;\n}\nint main()\n{\n int x = 20;\n int y = 30;\n cout << GetNumber(x) << " ";\n cout << GetNumber(y);\n return 0;\n}

Difficulty: Medium

Correct Answer: 21 31

Explanation:


Introduction / Context:
This question probes C++ overload resolution and shows that the best match is chosen based on parameter types, not on return types. Two overloads of GetNumber differ in their parameter types: one takes long int, the other takes int.


Given Data / Assumptions:

  • Both calls pass an int argument (x and y).
  • The int overload pre-increments and returns a float.
  • The long int overload pre-decrements and returns a long.


Concept / Approach:
C++ prefers an overload that requires no promotion or conversion for the parameter. Passing an int exactly matches GetNumber(int); selecting the long overload would require an integral promotion. Therefore, GetNumber(int) is called for both x and y, incrementing each before returning. The floating return type prints as a whole number with default formatting when the value is integral.


Step-by-Step Solution:
1) GetNumber(x) chooses the int overload: returns ++20 → 21 (as float). 2) GetNumber(y) chooses the int overload: returns ++30 → 31 (as float). 3) cout prints “21 31”.


Verification / Alternative check:
If x were explicitly cast to long, e.g., GetNumber((long)x), you would invoke the decrementing overload and see 19.


Why Other Options Are Wrong:
19 31 mixes different overloads; 20 30 ignores pre-increment; 21 29 decrements the second value; “Compile-time error” is incorrect because overload resolution is unambiguous.


Common Pitfalls:
Thinking return type participates in overload resolution (it does not) and overlooking that both calls use the same overload.


Final Answer:
21 31

More Questions from Functions

Discussion & Comments

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