Why does compiler not perform implicit conversion, when first operand is not a class object (member function operator overloading)?

Viewed 56

Let's conside the following member function:

Rational operator + ( const Rational & ) const;  //Rational is the class name

Complier translates a + b to a.operator+(b)

case 1: a + 14 //a is Rational class object.
This works fine, because 14 is implicitly converted to class type Rational (Am I correct ?)

case 2: 14 + a // a is a Rational class object.
This does not work because 14 is not a Rational class object.

My question : Why does the compiler not perform impicit conversion in case 2?

1 Answers

C++ does not make the assumption that operators are commutative. In order for x + a to work there must either be a built in operator + that is applicable (not the case), a user defined member operator of x that is applicable (not the case; int does not have members) or a operator defined outside of the class (seems to be missing in this case).

None of those cases applies for 14 + a which is why this fails. You could implement the operator outside of the class though to make this expression work:

class Rational
{
public:
    Rational operator + ( const Rational & ) const;
...
};

template<typename T>
Rational operator+(T o1, Rational const& o2)
{
    return Rational(o1) + o2;
}

Related