Molly P Molly P - 1 year ago 109
C++ Question

Nonmember friend function is always inline

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
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;
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"?

Answer Source

any function defined inside a class (member or non-member friend) is always implicitly inline. That's because class definitions are generally in header files, and you don't want any non-inline function definitions in a header file (having a non-inline function in a header leads to multiple definitions if the header is #included in more than one source file).

If you want a function to be non-inline, you need to define it outside of a class definition. If its a member or friend you still need to declare it inside the class, since members and friends must be declared in the class. You just don't want it defined in the class.

This all gets into the difference between a definition and a declaration in C++ -- they are two distinct things, though every definition is also implicitly a declaration, not every declaration is a definition. As a result, when the spec says 'declaration' it means 'declaration that is not also a definition'

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download