Oct 13, 2014 at 3:38am UTC
Hello everybody!
We've found that friendship could behave different with nested classes.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
#include<iostream>
using namespace std;
class B{
int b;
B():b(123456){}
friend class C;
};
class C:B{
void asd(){
cout<<B::b<<endl;
}
friend struct A;
};
struct A{
A(){
C c;
c.asd();
}
};
int main(){
A a;
}
Only when
class B
and
class C
are nested,
class B
and
class C
can have the
same friend
struct A
.
When they are nested,
class C
must be declared
forward when the friend of
class B
is
class C
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
#include<iostream>
using namespace std;
struct A{
//class C;
class B{
int b;
B():b(123456){}
friend struct A;
//friend class C;
};
class C:B{
void asd(){
cout<<B::b<<endl;
}
friend struct A;
};
A(){
C c;
c.asd();
}
};
int main(){
A a;
}
Why does friendship behave different with nested classes?
Especially: Why are nested classes implicit friends, when they are only friends of the class, that nests them?
Thank you very much!
Best regards,
http://ncomputers.org
Last edited on Oct 13, 2014 at 3:50am UTC
Oct 14, 2014 at 2:31am UTC
As the link given by MiiNiPaa explains, under 11.3[class.friends]/2
Declaring a class to be a friend implies that the names of private and protected members from the class granting friendship can be accessed in the base-specifiers and member declarations of the befriended class.
Because B granted friendship to A, the declaration of C (which is a member declaration of A) can access B's private member B::b.
Note that B doesn't need to be a member of A for this to happen, it's not "only when class B and class C are nested", but rather "only when class C is nested"
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
#include <iostream>
class B{
int b;
B() : b(123456){}
friend struct A; // this lets A::C::asd() see B::b
};
struct A{
class C:B{
void asd() { std::cout << B::b << '\n' ; }
friend struct A; // this lets A::A() see A::C::asd()
};
A() { C c; c.asd(); }
};
int main()
{
A a;
}
Last edited on Oct 14, 2014 at 2:37am UTC
Oct 14, 2014 at 4:01am UTC
Cubbi :
Thank you very much for your answer and your time!
Wow! I understand now friendship with nested classes better.
Best regards,
http://ncomputers.org
Last edited on Oct 14, 2014 at 4:07am UTC