Search code examples
c++friend

Private inheritance along class hierarchy, why friend is needed all along the hierarchy


Consider the following code:

#include <iostream>

class A{
    friend class C;
    int a{42};
};

class B: private A{
    friend class C;
};

class C: private B {
public:
    void print() {std::cout << a << '\n';}
};

int main() {
    C c;
    c.print();
}

According to this answer, the member variable A::a is "present" in all classes, but its visibility differ, i.e. is not visible in B or C unless we make B or C a friend of A. My question is why do I need to make C a friend of both A and B? I would've though the friend declaration in A would suffice. If I remove the friend class C; declaration from either A or B, the code fails to compile.


Solution

  • My question is why do I need to make C a friend of both A and B?

    Without B declaring C has a friend, C wouldn't see B as inheriting A. Even though C would see A::a, it would not see B::a.

    Indeed:

    • C inherits B, so anything public in B is accessible from C.
    • But B inherits privately from A. C being a friend of B makes C see this inheritance.
    • The access of A::a is private, so even though C sees A as its ancestor, it needs to be a friend of A to see A::a.