Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 551
Manarbek Avatar asked Sep 12 '25 16:09

Manarbek


1 Answers

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; }
  };
};
like image 133
molbdnilo Avatar answered Sep 15 '25 06:09

molbdnilo