Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

friend with class but can't access private members

Tags:

c++

friend

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;
}
like image 293
starcorn Avatar asked Jul 17 '10 10:07

starcorn


People also ask

Can friend classes access private members?

A friend class can access both private and protected members of the class in which it has been declared as friend.

How do you access private members in a classroom?

Private: The class members declared as private can be accessed only by the member functions inside the class. They are not allowed to be accessed directly by any object or function outside the class. Only the member functions or the friend functions are allowed to access the private data members of the class.

Can friend classes access public members?

A friend function in C++ is defined as a function that can access private, protected and public members of a class.

Can friend functions access private variables?

A friend function cannot access the private and protected data members of the class directly. It needs to make use of a class object and then access the members using the dot operator. A friend function can be a global function or a member of another class.


2 Answers

The signatures don't match. Your non-member function takes fun& fun, the friend declared on takes const fun& fun.

like image 60
Puppy Avatar answered Sep 23 '22 09:09

Puppy


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.)

like image 27
Brian Hooper Avatar answered Sep 23 '22 09:09

Brian Hooper