Question

Hi I have a code like this, I think both the friend overloaded operator and conversion operator have the similar function. However, why does the friend overloaded operator is called in this case? What's the rules?

Thanks so much!

class A{

    double i;
public:
    A(int i):i(i) {}
    operator double () const { cout<<"conversion operator"<<endl;return i;}                            // a conversion operator
    friend bool operator>(int i, A  a);                            // a friend funcion of operator >
};

bool operator>(int i, A  a ){
    cout<<"Friend"<<endl;
    return i>a.i;
}
int main()
{
    A  aa(1);
     if (0 > aa){
         return 1;
      }
}
Was it helpful?

Solution

No conversion is necessary for the overloaded operator> to be called. In order for the built-in operator> to be called, one conversion is necessary (the user-defined conversion operator. Overload resolution prefers options with fewer required conversions, so the overloaded operator> is used.

Note that if you were to change the definition of your overloaded operator> to be, for example:

friend bool operator>(double i, A  a);

you would get a compilation error because both the overloaded operator> and the built-in operator> would require one conversion, and the compiler would not be able to resolve the ambiguity.

OTHER TIPS

I am not claiming that my answer is supported by the standards, but lets think about it logically.

When you hit this line:

0 > aa

You have two options. Either you call the provided operator:

friend bool operator>(int i, A  a);

Which is 100% compatible, or you can do two conversions to reach your destination! Which one would you choose?

If you add a conversion operator then an object of type A may be converted to double when you least expect it.

A good program does not provide a way for his classes to be accidently used and the conversion operator opens up the opertunity for the class to be used in a whole host of unintended situations (normally situations where you would expect a compile time error are not because of the auto type conversion).

As a result conversion operators (and single argument constructors) should be treateed with some care because of situations were the compiler may do conversion when you least expect it.

It is called because it is an exact match in the context of the expression 0 > aa. In fact, it is hard to figure out how you came up with the "why" question. By logic, one'd expect a "why" question if the friend weren't called in this case.

If you change the expression to 0.0 > aa, the call will beciome ambiguous, because neuther path will be better than the other.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top