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
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.)
The friend version has access to the members of your class. A plain non-member does not. This can be useful.
By reading the definition of a Friend Function you will get the answer to your question.
friend function is used in object-oriented programming to allow access to private or protected data in a class from the outside. Normally, a function that is not a member of a class cannot access such information; neither can an external class. Occasionally, such access will be advantageous for the programmer. Under these circumstances, the function or external class can be declared as a friend of the class using the friend keyword. The function or external class will then have access to all information – public, private, or protected – within the class.
精彩评论