JM233333
JM233333

Reputation: 53

Why are friend functions "available" for derived classes only when using public inheritance?

When a derived class inherits from a base class via public access, the question is the same as that in Are friend functions inherited? and why would a base class FRIEND function work on a derived class object? . However, if it inherits via protected or private access, there will be a visibility error.

When it inherits via public access, the accessibility of private members of A is the same as if inheriting via private access. What's the difference between them?

class A {
private:
    int a;
    friend void f();
};

class B : private A {
};

void f() {
    B obj;
    int x = obj.a;
}

int main() {
    f();
    return 0;
}

Upvotes: 5

Views: 853

Answers (1)

Michael Kenzel
Michael Kenzel

Reputation: 15951

As already pointed out in the answer linked above, friendship is not inherited. Thus, a friend of A is not also a friend of B. Having B inherit from A via private access means that all members of A are accessible as private members of B [class.access.base]/1. Since f is not a friend of B, it cannot access private members of B [class.access]/1.1. Since f is not a friend of B, the base class A of B is also not accessible from f [class.access.base]/4. Since the base class A of B is not accessible from f, there's also no way you could get to the A subobject of a B (of which you could access the members) in f [class.access.base]/5

Upvotes: 7

Related Questions