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!

Recommended Answers

All 2 Replies

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.

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.