Search code examples
c++friend-function

Call a hidden friend function


Consider the following code:

struct A
{
    friend void foo(A& a) {}
};
struct B
{
    void foo()
    {
        A a;
        foo(a); // doesn't compile because "foo" friend function is hidden
    }
};

int main()
{
    A a;
    foo(a); // OK here
}

In function main, I can easily call friend function foo defined inside class A.

In function B::foo the same code doesn't compile because the friend function foo is hidden inside class B by its member function.

In there a way to call the original hidden function inside B, without renaming B::foo? I tried to use ::foo(a); or A::foo(a); but those don't compile neither.


Solution

  • In there a way to call the original hidden function inside B, without renaming B::foo?

    Yes there is by adding the declaration void foo(A& a) inside the member function void B::foo()as shown below. This also meets your requirement that you don't want to rename B::foo.

    Basically we're making use of forward declaration here.

    struct A
    {
        friend void foo(A& a) {}
    };
    
    struct B
    {
        void foo()
        {
            A a;
            void foo(A&); //added this declaration
            foo(a); //compiles now
        }
    };
    

    Working demo