Search code examples
c++inheritancec++17friend

Why does the derived class have access to the private field of the base class?


class Base {
 public:
  class FirstBase {
    friend class Base;
    int x = 10;
  };

  class SecondBase : public FirstBase {
   public:
    SecondBase() : FirstBase() {}
    void t() { std::cout << FirstBase::x; }
  };
};

This code compiles and works, but I don't understand why it works. Can explain or cite sources to read?

I use gcc version 11.4.0 std=C++17


Solution

  • Base is a friend of FirstBase, and SecondBase can access anything Base can access.

    From the latest draft:
    class.access, item 2:

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

    (Note that "nested" classes are members of the enclosing class.)

    with the footnote

    Access permissions are thus transitive and cumulative to nested and local classes.

    Note that the inheritance is irrelevant - this is also fine:

    class Base {
     public:
      class FirstBase {
        friend class Base;
        int x = 10;
      };
    
      class SecondBase {
       public:
        SecondBase() {}
        void t(FirstBase fb) { std::cout << fb.x; }
      };
    };