Search code examples
c++namespacesfriendfriend-function

Friend function still can't access private member


I have a simple C++ class, which I'm trying to add stream operators to, so it can be used with cout and cin

#include <iostream>

namespace testing_namespace {
    class test {
        friend std::ostream &operator<<(std::ostream &os, const test &o);
        friend std::istream &operator>>(std::istream &is, test &o);
    public:
        void doThing();
    private:
        int member;
    };
}

This is the implementation file:

std::ostream &operator<<(std::ostream &os, const testing_namespace::test &o) {
    return os << o.member;
}

std::istream &operator>>(std::istream &is, testing_namespace::test &o) {
    return is >> o.member;
}

void testing_namespace::test::doThing() {
    std::cout << member << " thing" << std::endl;
}

I'm getting an error on compilation:

In function 'std::ostream& operator<<(std::ostream&, const testing_namespace::test&)':
test.cpp:8:20: error: 'int testing_namespace::test::member' is private within this context
 return os << o.member;

with a similar error for operator>>. The doThing method compiles with no issues.

I'm not sure what I'm missing here - shouldn't friend functions be able to access the private members of the class test?


Solution

  • You need to define those functions under the namespace too. When you do that, you can omit the name of the namespace from test.

    namespace testing_namespace 
    {
      std::ostream &operator<<(std::ostream &os, const test &o) {
        return os << o.member;
      }
    
      std::istream &operator>>(std::istream &is, test &o) {
        return is >> o.member;
      }
    }