Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading