Home > Mobile >  Friend function from another namespace
Friend function from another namespace

Time:01-15

/** 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?

CodePudding user response:

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 shown here.

  •  Tags:  
  • Related