Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't functions be overloaded by return type? [duplicate]

Possible Duplicates:
Function overloading by return type?
Puzzle: Overload a C++ function according to the return value

Because I have a library which exposes a bunch of functions in the form of:

bool GetVal();
double GetVal();
int GetVal();
long GetVal();
//So on.

And now I have to wrap these. I'd rather not rewrite the same set of functions again. I'd like to do something like

template<class T>
T GetVal(){}

But I can't seem to get this working. Any ideas?

like image 319
nakiya Avatar asked Dec 02 '10 04:12

nakiya


People also ask

Why we Cannot overload a function on return type?

During compilation, the function signature is checked. So, functions can be overloaded, if the signatures are not the same. The return type of a function has no effect on function overloading, therefore the same function signature with different return type will not be overloaded.

Can you overload based on return type?

No, you cannot overload a method based on different return type but same argument type and number in java.

Why method overloading is not possible by changing the return type of method only Mcq?

It is not possible to decide to execute which method based on the return type, therefore, overloading is not possible just by changing the return type of the method.


2 Answers

You can't overload on return types as it is not mandatory to use the return value of the functions in a function call expression.

For example, I can just say

GetVal();

What does the compiler do now?

like image 138
Chubsdad Avatar answered Nov 13 '22 17:11

Chubsdad


The return type of functions is not a part of the mangled name which is generated by the compiler for uniquely identifying each function. Each of the following:

  • Number of arguments
  • Type of arguments
  • Sequence of arguments

are the parameters which are used to generate the unique mangled name for each function. It is on the basis of these unique mangled names that compiler can understand which function to call even if the names are same(overloading).

like image 42
Alok Save Avatar answered Nov 13 '22 17:11

Alok Save