2

In C++, we are allowed to define a friend function inside the class definition like:-

class A {
public:
    A(int a): mem(a){}
    ~A() {}
    friend void fun() {}
private:
    int mem;
};
void fun();

and then we can call this function, just like any regular function.

fun();

Can someone explain about (with examples):

  1. In what cases do we need to define friend function inside the class definition.

  2. What is special about this kind of definition which can not be achieved with just declaring function as friend in class and then defining the function outside.

Ðаn
  • 10,934
  • 11
  • 59
  • 95
Dinesh Maurya
  • 822
  • 8
  • 24
  • 1
    Look for [the answer](https://stackoverflow.com/a/52068027/1906174) to a related question. The main consideration are implicit conversions to `fun` parameters and ADL. Also! `void fun()` isn't really equivalent to in-class definition -- `inline void fun()` is. – Wormer Aug 15 '19 at 17:49

1 Answers1

2

Assuming that you already know what is a friend function, there is absolutely no special meaning to your example: what you have is a regular friend function, with its declaration and definition combined.

Recall that friendship needs to be declared inside the class that "friends" a function. After that, the function can be defined at some place, for which you have two choices:

  • Outside the class - that is the common way of defining a friend function, or
  • Inside the class - that is what your example has.

Basic considerations for going with one approach vs. the other are the same as the rules that you use to decide between defining a member-function inside or outside the class.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523