Access to nested classes (which behave like friends but are not)

Without much delay, here is the code that I don’t know why it does what it does:

#include <iostream> class A { private: void print() { std::cout << "A.print() called" << std::endl; }; public: template<typename Foo> class B; //NOTE: no friend! public: A(); B<double>* bd; B<int>* bi; }; template<typename Foo> class A::B{ A* callback; public: B(A* a):callback(a){}; void print() { callback->print(); }; // Why is this working ??? }; A::A():bd(new B<double>(this)),bi(new B<int>(this)){} int main(int argc, char **argv) { A a; // a.print(); // error: 'void A::print()' is private a.bd->print(); a.bi->print(); A::B<char> c(&a); c.print(); A::B<double> d = *a.bd; d.print(); return 0; } 

Well, he creates this conclusion:

 A.print() called A.print() called A.print() called A.print() called 

But why?

Background

First, I started my journey through the rabbit hole when I encountered a problem that I had to deal with friend s. Therefore, I am reading a friend's declaration, not declaring ahead (and the answers mentioned here and here ). Therefore, trying to create a simple example (the result of which you see above), I found that I really do not need a friend at all.

Question

So, here is the main question: Why does the A::B instance have access to the private function A A::print() ? (although I understand that I could misunderstand that my children are children, unlike the basic or received ones)

+1
c ++ class instance parent-child
Feb 07 '13 at 19:01
source share
2 answers

because the nested class is a member of the enclosing class

standard $ 11.7.1

"The nested class is a member and as such has the same access rights as any other member. Members of the closing class do not have special access to members of the nested class, normal access rules must be followed."

and ordinary access rules indicate that:

"A member of the class can also access all the names that the class has access to ..."

The standard provides specific examples:

 class E { int x; class B { }; class I { B b; // OK: E::I can access E::B int y; void f(E* p, int i) { p->x = i; // OK: E::I can access E::x } }; } 
+2
Feb 07 '13 at 19:09
source share
— -

A nested class (or inner class) has access to the member classes in which it is nested. In a sense, they are already familiar with this class. This is similar to the fact that any object A has access to private individuals of any other object A

You use friend for classes that are defined outside of your class that you want to access your privates. Here is a simple example:

 struct B; class A { int x; friend struct B; }; struct B { void someFunc() { A a; ax = 5; } }; int main(int argc, const char* argv[]) { B b; b.someFunc(); return 0; } 

Without creating friend B A , he will not be able to access A member x .

+2
Feb 07 '13 at 19:06
source share



All Articles