1

I have a doubt on the result of the question below. When calling function f from main, the call goes to f(B &) although I have int operator overloaded and f(int) is defined first.

If I comment out the f(B &) function, then the call goes to f(int) and prints 5.

#include <iostream>
using namespace std;
class A{
    int y;
    public:
    A(int y=2):y(y){}
    int getValue(){
        cout<<y<<endl;
    }
};
class B{
    int x;
    public:
    A a;
    B(int x=5):x(x){}
    operator int(){
        return x;
    }
};
void f(int x){
    cout<<x<<endl;
}
void f(B &b){
    b.a.getValue();
}
int main() {
    B b;
    f(b);
}

I was expecting it to go to f(int) function and print 5 but it instead prints 2. Why it does not go to f(int) instead of f(B &). Why is this behavior happening, can anyone please explain?

1 Answers1

4

Function overload resolution is based on which function is a better match, not which function is "defined first".

You're passing a B, so f(B&) is an exact match.

f(int) is not as it requires a conversion.

There's nothing in your program to trigger said conversion, though it would be attempted if f(B&) did not exist.


By the way, your getValue is actually more like printValue. It currently has an int return type, but does not actually return anything, so your program has undefined behaviour. You can fix this by making it return void, but you'd probably be better off making it return y instead.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055