Search code examples
c++friend

friend with class but can't access private members


Friend functions should be able to access a class private members right? So what have I done wrong here? I've included my .h file with the operator<< I intent to befriend with the class.

#include <iostream>

using namespace std;
class fun
{
private:
    int a;
    int b;
    int c;


public:
    fun(int a, int b);
    void my_swap();
    int a_func();
    void print();

    friend ostream& operator<<(ostream& out, const fun& fun);
};

ostream& operator<<(ostream& out, fun& fun)
{
    out << "a= " << fun.a << ", b= " << fun.b << std::endl;

    return out;
}

Solution

  • In here...

    ostream& operator<<(ostream& out, fun& fun)
    {
        out << "a= " << fun.a << ", b= " << fun.b << std::endl;
    
        return out;
    }
    

    you need

    ostream& operator<<(ostream& out, const fun& fun)
    {
        out << "a= " << fun.a << ", b= " << fun.b << std::endl;
    
        return out;
    }
    

    (I've been bitten on the bum by this numerous times; the definition of your operator overload doesn't quite match the declaration, so it is thought to be a different function.)