Reputation: 1193
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?
Upvotes: 12
Views: 2825
Reputation: 81379
Here is Fraction
with the operator as a member function:
class Fraction
{
Fraction(int){...}
Fraction operator -( Fraction const& right ) const { ... }
};
With it, this is valid code:
Fraction x;
Fraction y = x - 42;
and its equivalent to x.operator-( Fraction(42) )
; but this is not:
Fraction z = 42 - x;
Because 42
has no member function operator -
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
Fraction z = 42 - x;
turns into this
Fraction z = Fraction(42) - x;
which is equivalent to operator-( Fraction(42), x )
.
Upvotes: 18