c++ - Access of nested classes (which behave like friends, but aren't) -
without long delay, here code have no clue why does:
#include <iostream> class { 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 working ??? }; a::a():bd(new b<double>(this)),bi(new b<int>(this)){} int main(int argc, char **argv) { a; // a.print(); // error: ‘void a::print()’ private a.bd->print(); a.bi->print(); a::b<char> c(&a); c.print(); a::b<double> d = *a.bd; d.print(); homecoming 0; }
well, creates ouput:
a.print() called a.print() called a.print() called a.print() called
but why?
backgroundi started journey downwards rabbit hole when encountered problem through have friend
s. read friend declaration not forwards declaring (and mentioned answers here , here). while trying set easy illustration (the result of see above), found don't seem need friend
@ all.
so here bottom line question: why instance of a::b
have access a
's private function a::print()
? (although realize might misunderstand my children are--children opposed base vs. derived)
because nested class fellow member of enclosing class
standard $11.7.1
"a nested class fellow member , such has same access rights other member. members of enclosing class have no special access members of nested class; usual access rules shall obeyed"
and usual access rules specify that:
"a fellow member of class can access names class has access..."
specific examples has been given in standard:
class e { int x; class b { }; class { 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 } }; }
c++ class instance parent-child
No comments:
Post a Comment