Search code examples
c++friend-function

Friend function from another namespace


/** module.h */
#pragma once

class A {
  friend void helpers::logValue(const A &);
  int _val;

public:
  A() {}
};

namespace helpers {
  static void logValue(const A &a) {
    std::cout << a._val;  // <== ERROR: '_val' is not accessible
  }
}

How do I declare the friend function in another namespace?


Solution

  • One possible way of solving this is as shown below:

    class A;//forward declaration for class A
    namespace helpers{
    static void logValue(const A &a); //declaration
    }
    ///////////////////////////////////////////
    
    class A {
        
      friend void helpers::logValue(const A &);
    
      int _val;
    };
    
    namespace helpers {
      static void logValue(const A &a) {
        std::cout << a._val;  // works now
      }
    }
    

    The output of the above program can be seen here.