user1086635
user1086635

Reputation: 1544

How to use friend function of local class?

Since a friend function can be declared in a local class as shown in the following example. How can it be used to access members of local class when it is defined in the function definition which cannot be accessed outside of it?

void foo()
{
    void bar();

    class MyClass
    {
        int x;
        friend void bar();
    };
}

void bar() { // error: cannot access local class here }

int main()
{
    //..
}

Upvotes: 0

Views: 744

Answers (3)

Potatoswatter
Potatoswatter

Reputation: 137810

A friend function declaration in a local class is still useful for a function template specialization. This is only true in C++11, since in C++03 local types cannot be template arguments.

template< typename t >
int bar( t &o ) {
    return ++ o.x;
}

int main()
{
    class MyClass
    {
        int x;

        friend int bar<>( MyClass &o );

    public:
        MyClass() : x( 0 ) {}
    };

    MyClass m;

    std::cout << bar( m ) << ", " << bar( m ) << '\n';
}

http://ideone.com/vcuml

Otherwise, I don't see how such declarations can accomplish anything.

Upvotes: 1

BЈовић
BЈовић

Reputation: 64223

There are no ways for the function bar() to access the class MyClass defined in the function foo(). If you need to access that class, then take it out of the foo() function.

Upvotes: 1

escargot agile
escargot agile

Reputation: 22379

MyClass is not accessible outside foo(), therefore you cannot access any of its methods from outside foo().

If you want to use bar() once the call to foo() is complete, make MyClass inherit from some base class or implement some interface, and then you'll be able to call its methods which implement the interface.

Upvotes: 1

Related Questions