I am very new to C++, and when I am trying to learn the friend function, I saw from friend description on Cppreference that:
2) (only allowed in non-local class definitions) Defines a non-member function, and makes it a friend of this class at the same time. Such non-member function is always inline.
class X {
int a;
friend void friend_set(X& p, int i) {
p.a = i; // this is a non-member function
}
public:
void member_set(int i) {
a = i; // this is a member function
}
};
Does this mean that all friend functions always have to be inline? In another word, must the friend functions be defined completely inside the class?
However, I also found an instance where the friend function is defined outside the class from Cplusplus
// friend functions
#include <iostream>
using namespace std;
class Rectangle {
int width, height;
public:
Rectangle() {}
Rectangle (int x, int y) : width(x), height(y) {}
int area() {return width * height;}
friend Rectangle duplicate (const Rectangle&);
};
Rectangle duplicate (const Rectangle& param)
{
Rectangle res;
res.width = param.width*2;
res.height = param.height*2;
return res;
}
I am really confused by this conflict. Is my understanding of inline wrong? What does it mean by "a nonmember friend function defined inside the class is automatically inline"?