Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memberspaces may access private members of parent class

Tags:

c++

idioms

I've been reading this article, and was playing around with the memberspace idiom for a while when I noticed something that surprised me within this snippet (which compiles without problems: http://ideone.com/hRiV5B):

class HugeClass
{
    public:
        struct memberspace
        {
            int f() const { return parent.f; }

            private:
                friend HugeClass;
                explicit memberspace(HugeClass & parent)
                : parent(parent) {}
                HugeClass & parent;
        } memberspace;

        HugeClass() : memberspace(*this), f(42) {}

    private:
        int f;
};

I would have expected a compiler error that the access of HugeClass::f is not allowed because f is private in that context.

HugeClass is a friend of memberspace, so HugeClass may call the private constructor of memberspace, but why does it work the other way around without explicitly declaring memberspace a friend of HugeClass?

like image 440
nijansen Avatar asked Jul 17 '13 12:07

nijansen


1 Answers

By language rules in C++11.

A nested class is a member and as such has the same access rights as any other member. Example:

class E {
   int x;
   class B { };
   class I {
     B b; // OK: E::I can access E::B
     void f(E* p, int i) 
     {
        p->x = i; // OK: E::I can access E::x
     }
   };
};

And in C++03 was

The members of a nested class have no special access to members of an enclosing class, nor to classes or functions that have granted friendship to an enclosing class; the usual access rules (clause 11) shall be obeyed.

So, example from C++11 should not work with c++03 compilers.

like image 137
ForEveR Avatar answered Sep 21 '22 08:09

ForEveR