Search code examples
c++c++11friendlocal-class

What is the reason to we can not define friend function in local class?


I have a following snippet code of c++. Declared a class inside main() function.

What is the reason to we can not define friend function in local class?

#include<iostream>

int main()
{
    class Foo
    {
        void foo() {} // Ok
        friend void Bar(){}; // Error
    };
}

Solution

  • There's a practical reason. First and foremost, an inline friend definition cannot be found by either qualified or unqualified lookup. It can only by found by ADL. So if we take the class from your example, put it in global scope and try to call Bar:

    class Foo
    {
        friend void Bar(){};
        void foo() {
          Bar();
        }
    };
    

    We'll be notified that Bar was not declared in that scope. So if it was in a local class. You can't call it from the members. You can't call it inside the function. The only way you may call it involves either some hoops or ADL. So the language just doesn't allow for it. It's not deemed a useful feature.