0

I wrote two functions like that

int absolute(int a) { return (a < 0) ? -a:a;}
int absolute(int &a) { return (a = (a < 0) ? -a:a;}

The two function have the same name and the same type,
When I do like that:

int main() {
    int a = -1;
    absolute(a);
    return a;
}

there is a error when I compile it, BUT it is not because of the two function but the calling absolute(a);
I'm wondering how to call these two functions correctly, thx!

3
Contributors
2
Replies
4
Views
5 Years
Discussion Span
Last Post by PrimePackster
2

Very often, if a function call is ambiguous to the compiler, it is also ambiguous to the programmer. In your code, there are two functions that do two very different things, the first returns the absolute value of a, and the second makes the given variable positive. Why are these functions called the same? To me, this is ambiguous and weird, and I wouldn't accept it in any reasonable interface. Don't abuse overloading in this way.

As for actually fixing it, well, the answer is that you need to explicitely cast the function in order to tell the compiler what overload it should look for. If you are not familiar with function-pointers, this will look alien to you, but, otherwise, here is the solution:

int main() {
    int a = -1;
    (( int (*)(int) ) absolute) (a);
    // or: 
    (( int (*)(int&) ) absolute) (a);
    return a;
}

Now, you might also observe why it is easier to just give them different names. Only use overloading when the function parameters are different enough that there is very little chance of ambiguity.

0

Tell me! If you were a compiler, which one would you choose from the above functions??? What logic will you depend on??? If you can't decide one with considerable reasoning, your compiler too can't do it...... The parameters should be distinct enough to use the function overloading..... For your case, the only change is how function is called with "Call by Value" or "Call by reference" Methord.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.