Can a friend class object access base class private members on a derived class object?

后端 未结 5 1846
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-19 21:39

I\'m surprised that the code below compiles.

It seems that a class befriended to the (publicly inherited) base class can access a member of the base class provided an in

5条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-19 22:28

    You write:

    It seems that somehow friendship is inherited and a friend class can access a member of the derived class.

    But it rather should be:

    It seems that a class befriended to the (publicly inherited) base class can access a private member of the base class provided an instance of the derived class.

    Or:

    It seems that a class befriended to another class can access the private members of its instances.

    This relates to your question:

    In short, how is d.b_var valid within F::func(D& d) ?

    Because d.b_var is a member of an instance of class B (via polymorphism) to which instances of class F have access (via friend-status).

    This doesn't work with d.d_var, because the friendship to the base class is not inherited and instances of class F therefore don't have access to private members of d.

    This doesn't work with private (or protected) inheritance, because thereby another "layer of access restriction" is added. In addition, you then need to grant access to the derived class' privately inherited members as well (which d.b_var then is). For example by making also D a friend to F.

    For reference:

    • http://en.cppreference.com/w/cpp/language/friend
    • http://en.cppreference.com/w/cpp/language/derived_class

提交回复
热议问题