What is the difference between defining friend function inside the class or declaring inside and define outside of the class. Also why it is possible to place definition inside the class, as friend function are not member of the class.
A friend function in C++ is a function that is declared outside a class but is capable of accessing the private and protected members of the class.
Friend functions can be defined (given a function body) inside class declarations. These functions are inline functions. Like member inline functions, they behave as though they were defined immediately after all class members have been seen, but before the class scope is closed (at the end of the class declaration).
A friend function can be declared in the private or public section of the class. It can be called like a normal function without using the object. A friend function is not in the scope of the class, of which it is a friend. A friend function is not invoked using the class object as it is not in the scope of the class.
A friend function is a special function in C++ which in-spite of not being member function of a class has privilege to access private and protected data of a class. A friend function is a non member function or ordinary function of a class, which is declared as a friend using the keyword “friend” inside the class.
There are subtle implications of the following regarding member access.
C++11 §11.4/5
A friend function defined in a class is in the (lexical) scope of the class in which it is defined. A friend function defined outside the class is not (3.4.1).
Still there as of C++17 §14.3/7
Such a function is implicitly an inline function (10.1.6). A friend function defined in a class is in the (lexical) scope of the class in which it is defined. A friend function defined outside the class is not (6.4.1).
Consider the condenced example from cppreference [Friend function definition], where f1
finds class static member and f2
finds global variable.
int i = 3;
struct X {
friend void f1(int x) {
i = x; // finds and modifies X::i
}
friend inline void f2(int);
static const int i = 2;
};
inline void f2(int x) {
i = x; // finds and modifies ::i
}
Of course this can't affect design desicions for the friend function. The main consideration between choices is a difference in name look up as already mentioned in the other answer. Don't forget the inline for f2
to match those of f1
implied by default.
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