2

I am confused by the following sentence in our lectures

By way of Functions of the Name operator@ the named operator @ (excluding = () [] ? : . -> .* ::) can be overloaded for datatypes that have not been 'built in'.

I realize that the operator @ refers to the likes of '+ - * / ^ ...etc', and I understand how and why these are overloaded. But I am annoyed by the "(excluding = () [] ? : . -> .* ::)" part that is mentioned above. What is meant by it, and why are those said operators excluded?

I mean I declare

something operator+(something a, something b)

and I do not see a big difference in the way I declare

something operator[] (something c)

It is said that the likes of [], (), -> and = can only be overloaded with member functions, but the operator + that I mentioned above is also only overloaded via a member function, is it not?

Christophe
  • 68,716
  • 7
  • 72
  • 138
user9078057
  • 271
  • 1
  • 10

1 Answers1

2

There are two ways to overload operators:

  • as "free" function (i.e. non-member), outside of the class for which you want to overload them,
  • as member function.

The link above clarifies in a nice table that the overload is possible in the form of member functions for =, (), [], and -> but forbidden as free function.

In addition, the scope resolution operator :: as well as member access ., member access trhough pointer to member .*, and the ternary conditional operator x ? y : z cannot be overloaded at all.


Edit: Here an example, with operator* defined as member function and operator+ as non member function:

class Rational {
    int p; 
    int q; 
public:  
    Rational (int d=0, int n=1) : p{d}, q{n} { } 
    Rational operator*(const Rational& r) const {    // for curent object * r
        return Rational(p*r.p,q*r.q); 
    }
    int numerator() const {return p; }
    int denominator() const { return q; } 
}; 

Rational operator+(const Rational &a, const Rational &b) {   // for object a + object b
    return Rational(a.numerator()*b.denominator()+b.numerator()*a.denominator(),
                                                      a.denominator()*b.denominator());
}
Christophe
  • 68,716
  • 7
  • 72
  • 138