I was reading the C++ FAQ. There I found a point in the guideline for operator overloading uses:
If you provide constructive operators, they should allow promotion of the left-hand operand (at least in the case where the class has a single-parameter ctor that is not marked with the explicit keyword). For example, if your class Fraction supports promotion from int to Fraction (via the non-explicit ctor Fraction::Fraction(int)), and if you allow x – y for two Fraction objects, you should also allow 42 – y. In practice that simply means that your operator-() should not be a member function of Fraction. Typically you will make it a friend, if for no other reason than to force it into the public: part of the class, but even if it is not a friend, it should not be a member.
Why has the author written that operator-() should not be member function?
What are the bad consequences if I make operator-() as member function and what are other consequences?
Here is
Fractionwith the operator as a member function:With it, this is valid code:
and its equivalent to
x.operator-( Fraction(42) ); but this is not:Because
42has no member functionoperator -in it (of course, its not even a class).However, if you declare your operator as a free function instead, conversion operations apply to both of its arguments. So this
turns into this
which is equivalent to
operator-( Fraction(42), x ).