Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Significance of overloading operator - () as free function & not a member function?

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?

like image 266
Abhishek Gupta Avatar asked Jun 09 '12 05:06

Abhishek Gupta


People also ask

What is the significance of operator overloading?

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.

Can free functions be overloaded?

You can overload both member functions and free functions.

Can a free function be overloaded C++?

@Xeo: Yes, you can. I've tried it and it works.

Why do we need operator overloading in C++?

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).


1 Answers

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 ).

like image 125
K-ballo Avatar answered Sep 30 '22 18:09

K-ballo