strange compiler error with friend function

Viewed 43

The following code is rejected by GCC/Clang/MSVC though it seems to be able to compile.

class B {
};
class C : private B {
    friend B& to_B(C& c) {
        return static_cast<B&>(c);
    }
};
class D : private C {
    friend C& to_C(D& d) {
        return static_cast<C&>(d);
    }
    friend B& to_B(D& d) {
        return to_B(to_C(d));
    }
};

Why the compilation fails?

GCC error message:

<source>:12:12: error: 'class B B::B' is private within this context
   12 |     friend B& to_B(D& d) {
      |            ^
<source>:3:7: note: declared private here
    3 | class C : private B {
      |       ^
1 Answers

I can't find chapter and verse to back it up, but C's private inheritance makes B completely private if it's looked up from within the definition of D.
(Essentially, B is first looked up in the inheritance chain, and since name lookup stops at the first match, it is private to C. The global definition is never considered.)

You can make it compile by modifying the name lookup procedure with an explicit scope:

friend ::B& to_B(D& d) 
Related