How to use/access inner friend function of class in c++?

Viewed 31

We can declare and define a friend function inside a class, like below

class C
{
    friend void F() {cout<<"inner friend func"<<endl;}
};

how to access/use this inner friend func?

C::F() //error: 'F' is not a member of 'C'
C().F()//error: 'class C' has no member named 'F'
2 Answers

The friend decalration declares F() as non-member function, then both C::F() and C().F() won't work. And you have to add a declaration in namespace scope for calling it because it's not visible for name lookup (except ADL, but F() takes no parameters then ADL doesn't work for it).

A name first declared in a friend declaration within a class or class template X becomes a member of the innermost enclosing namespace of X, but is not visible for lookup (except argument-dependent lookup that considers X) unless a matching declaration at the namespace scope is provided

and

Names introduced by friend declarations within a non-local class X become members of the innermost enclosing namespace of X, but they do not become visible to ordinary name lookup (neither unqualified nor qualified) unless a matching declaration is provided at namespace scope, either before or after the class definition. Such name may be found through ADL which considers both namespaces and classes.

E.g.

void F();
class C
{
    friend void F() {cout<<"inner friend func"<<endl;}
};

Then call it like

F();

LIVE

Declaring the function as a friend does not make it part of the class. You need to declare it outside:

#include <iostream>

using std::cout;
using std::endl;

class C
{
    friend void F() {cout<<"inner friend func"<<endl;}
};

void F();

int main() {
    F();
}

Or better, put also the definition outside of the class.

Related