If I have two Classes as follows with inheritance:
class A
{
...
}
class B : public A
{
...
}
And a third class with defined as a friend class A:
class C
{
friend class A;
}
Will I be able to access from class B (which is also an object of type A) all members of class C as if I had defined class B the friend Class in the first place?
friendship is neither inherited nor transitive. It is strictly one-one relationship between two classes.Reference: “The C++ Programming Language” Bjarne Stroustrup
More explanation (mine): If
friendship were not one-one, it would be the end of encapsulation. Note thatBclass can accessprivatemembers ofAonly if the class declaration ofAdeclaresBasfriend.Bcannot enforcefriendship onA.Now, if friendship could be inherited, then someone just needs to inherit
Bto access private members ofA, withoutAhaving any say in preventing it. Also, allowingfriendship to be transitive would lead to other problems, since nowBcould have afriendC, who in turn could have afriendD, all the way toZ. All ofB,C,D, …,Zcan now accessA‘sprivatemembers, which would be a disaster.