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?
Operator overloading facilitates the specification of user-defined implementation for operations wherein one or both operands are of user-defined class or structure type. This helps user-defined types to behave much like the fundamental primitive data types.
You can overload both member functions and free functions.
@Xeo: Yes, you can. I've tried it and it works.
It allows you to provide an intuitive interface to users of your class, plus makes it possible for templates to work equally well with classes and built-in/intrinsic types. Operator overloading allows C/C++ operators to have user-defined meanings on user-defined types (classes).
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 )
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With