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
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 withinF::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: