user1899020
user1899020

Reputation: 13575

Is a local class in a method of a class a friend of this class?

I have an outer class A. It has a method A::fun. In this method, it has a local or inner class B. My question is: Is B a friend of A?

I think it is not. Is it right? If so, I think let class B a friend of A is very beneficial since B can access to A's private and protected members. And moreover, sinceB is local in a methods, it is not accessible by others and thus safe as a friend of A. How to work around to let B access to A's private and protected members?

Upvotes: 9

Views: 557

Answers (3)

Pierre Fourgeaud
Pierre Fourgeaud

Reputation: 14510

No they are not friends.

But local classes have the same access to the names outside the function as the function itself.

The standard says :

9.8 Local class declarations [class.local]

A class can be declared within a function definition; such a class is called a local class. The name of a local class is local to its enclosing scope. The local class is in the scope of the enclosing scope, and has the same access to names outside the function as does the enclosing function. Declarations in a local class shall not odr-use (3.2) a variable with automatic storage duration from an enclosing scope.

The big difference to take in count is that your local class will only be accessible inside the function.

But after that :

  • A friend of a class is a function or class that is given permission to use the private and protected member names from the class.
  • The local class is in the scope of the enclosing scope, and has the same access to names outside the function as does the enclosing function. That is, it can access to protected and private members of the class the function belongs.

Upvotes: 14

Alok Save
Alok Save

Reputation: 206566

No they are not friends. But does it matter?
Not really! consider these facts:

  1. Within the member function you will always have access to the members of the class to which the function belongs.
  2. You cannot access the local class anywhere beyond the function.

So it hardly matters if they are friends or not. You are always going to be referring the outer class members inside its member function.

Online Sample:

class A
{
    int i;
    void doSomething()
    {
        class B{public: int ii;};
        B obj;
        obj.ii = i;
    }
};

int main()
{
    return 0;
}

Upvotes: 6

Sebastian Redl
Sebastian Redl

Reputation: 72044

This compiles in Clang:

class A {
  typedef int Int;
  void fn();
};

void A::fn() {
  class B {
    Int i;
  };
}

The inner class has access to A's private members, but not because it is a friend, but because it is considered a member. Since members of a class have access to private members, this includes inner classes as well as local classes of member functions.

See [class.access]p2.

Upvotes: 3

Related Questions