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?
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 :
No they are not friends. But does it matter?
Not really! consider these facts:
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;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With