Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access rights of a nested class of a nested class

In C++ a nested class has access rights to all members of the enclosing class. Does this also apply to a nested class of a nested class?

This code

#include <iostream>

class A
{
public:
    class B
    {
    public:
        B() { std::cout << A::x << std::endl; }

        class C
        {
        public:
            C() { std::cout << A::x << std::endl; }

        };

    };

private:
    static const int x { 0 };

};

int main()
{
    A::B b;

    A::B::C c;
}

compiles without warning on g++ 7.2. However, it is unclear to me that this conforms to the standard. The standard draft (N4727 14.7) says:

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

However, in the example above C is not a member of A, it is a member of a member. Is the standard ambiguous here? Is g++ behavior portable?

like image 203
Robert E. Brown Avatar asked Mar 31 '18 08:03

Robert E. Brown


1 Answers

However, in the example above C is not a member of A, it is a member of a member.

Yes this is well-defined behavior; the access right is transfered from B.

According to the standard [class.access]/2,

A member of a class can also access all the names to which the class has access.

And [class.mem]/1,

Members of a class are data members, member functions, nested types, enumerators, and member templates and specializations thereof.

C is a nested class of B, it's also the member of B, then C can access names what B could access to, including A::x. For the same reason, C::C is the member of C, it could access names what C could access to, so accessing A::x in C::C is fine.

like image 196
songyuanyao Avatar answered Oct 24 '22 19:10

songyuanyao