Search code examples
c++namespacesc++17friendforward-declaration

Allowing access to protected member function for class outside of namespace


Consider the following code:

namespace A
{
  class B
  {
  protected:
    friend class C;
    static void foo();
  };
}

class C
{
public:
  C() { A::B::foo(); }
};

int main()
{
  C c;
  return 0;
}

As currently constructed, this code will not compile - the friendship declared in class B applies to a (currently non-existent) A::C, and not the C in the global namespace. How can I work around this effectively, assuming I cannot add C to non-global namespace? I have tried using friend class ::C;, but the compiler does not like that. I have also tried forward declaring class C; before the namespace A scope, but that does not appear to work either.


Solution

  • Adding a forward declaration for class C worked for me, what compiler are you using?

    class C;
    
    namespace A
    {
      class B
      {
      protected:
        friend class ::C;
        static void foo();
      };
    }
    
    // ...
    
    

    Live demo


    Edit: as Vlad points out, both friend C and friend ::C also work, provided you have that forward declaration in place. But friend class C doesn't, I'll pass that one over to the language lawyers.