Search code examples
c++friendnon-member-functions

friend function, cpp


We had an assignment in school implementing a Matrix class that overloads all arithmetic operators. What I did was to (for example) define += as a member function, and then define + as a non-member function that uses += function (both in the same file, but + outside the class). The school staff did something similar, only they've declared '+' as a friend function (and also used the implementation of +=).

Since both implementation work perfectly, I am trying to understand what does a friend function gives me that a non member function does not? When should I prefer each over the other?

Thanks! Yotam


Solution

  • It is preferable not to declare functions friends, if they can be implemented in terms of the class's public interface (such as operator+ in terms of member operator+=.

    Somehow with operators sometimes people tend to assume that when implemented as free functions they need to be automatically declared friends. E.g you might hear that operator<< cannot be implemented as a member function (because the left-hand operand is an ostream), hence it needs to be a free friend function. In reality it only needs to be a friend if it needs access to private/protected members and member functions.

    (I suspect that might be because overloaded operators, due to their special call syntax, don't feel like normal functions and seem to have some kind of magical bond with its operands that needs to be expressed in the class definition.)