Search code examples
c++friend

Do nested classes obtain friendship relations of outer class?


#include <iostream>
#include <string>

class A {
    friend class B;
    std::string m = "Hello";
};

struct B {
    struct N {
        void f(){
            A a;
            std::cout << a.m << std::endl;
        };
    };
};

int main() {
    B::N().f();
}

Is N allowed to access m?

EDIT

Okay I ran it in cpp.sh and obviously it works. Is there a generic rule to understand how friendship relations are obtained?


Solution

  • The standard is pretty clear that friendship is not inherited:

    14.3/10: "Friendship is neither inherited nor transitive"

    But a nested class is not inheritance. It is a member. If a class is a friend, its members have access to the class's friends. Therefore, the inner/nested class has access.

    Straight from the standard:

    14.3/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. Example:

    class A {
        class B { };
        friend class X;
    };
    
    struct X : A::B {  // OK: A::B accessible to friend
        A::B mx;       // OK: A::B accessible to member of friend
        class Y {
          A::B my;     // OK: A::B accessible to nested member of friend
        };
    };