C++ function overloading rules: given a function with header int function(double d, char c), which of the following additional function headers may legally coexist in the same program?

Difficulty: Medium

Correct Answer: int function(int d, char c)

Explanation:


Introduction / Context:
Function overloading in C++ allows multiple functions to share the same name as long as their parameter lists differ in number or types. The return type alone is not part of the function signature for overloading resolution. This question verifies your understanding of which changes create a distinct overload and which do not.


Given Data / Assumptions:

  • Existing declaration: int function(double d, char c).
  • We are considering additional declarations with the same name but different signatures.
  • Standard C++ overload resolution rules apply; namespaces and default parameters are not in play here.


Concept / Approach:
An overload must differ in its parameter types or count. Changing only the return type does not create a valid overload and leads to a redefinition error because the function name and parameter list still collide. Therefore a second function that keeps parameters (double, char) but changes the return type to char is illegal. However, changing a parameter type, such as using int in place of double for the first parameter, produces a distinct signature and is permitted.


Step-by-Step Solution:
Compare option (a): char function(double d, char c) — same parameters as the original, only the return type differs.Recognize that return type alone does not differentiate overloads; this is not allowed.Compare option (b): int function(int d, char c) — parameter list differs in the first type (int vs double), creating a distinct signature.Conclude that only option (b) is a valid additional function in the same program.


Verification / Alternative check:
Attempting to compile both int function(double, char) and char function(double, char) in the same scope will yield a redeclaration error. Replacing the first parameter type with int compiles successfully, demonstrating legal overloading.


Why Other Options Are Wrong:

  • Option (a) fails because only the return type is changed.
  • Option (c) claims both are valid, which is incorrect.
  • Option (d) claims neither, which ignores the valid distinction in (b).


Common Pitfalls:
Assuming that different return types are sufficient for overloads. Overload resolution relies on the argument types at the call site, not on the desired return type.


Final Answer:
int function(int d, char c).

More Questions from Object Oriented Programming Using C++

Discussion & Comments

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