2

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?

Krishna Kanth Yenumula
  • 2,533
  • 2
  • 14
  • 26
  • You may want to add `language-lawyer` tag, since the answer will probably involve a lot of standard-ese. – Eljay May 22 '21 at 13:56

1 Answers1

1

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;
}

fabian
  • 80,457
  • 12
  • 86
  • 114