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;
}
f
is not a friend ofB
, sof
cannot access private base classes or members ofB
, sof
cannot accessB::a
since it would need access to the private base class. – AlexineB
derive fromA
, then why would you expectf
to be able to see that. When you do not derive publicly from a class, there no IS-A relationship between those classes. By the way, whenever possible, it is preferable to replace private or protected inheritance by containment. You want to avoid tight coupling as much as possible. – Argumentative