Friend Functions

Can someone explain to me what a friend function is used for? I am new to classes and I am confused of what a friend function is. So for example, what would this be for:

1
2
3
4
5
6
7
8
class Date {
public:
   friend bool equal(const Date&, const Date&);
private:
   int month;
   int day;
   int year;
};


Also I don't understand what equal is for. My professor showed us this:

if(equal(date1, date2)) { ...

If someone could explain this that would be awesome!
basically non-member functions don't have access to privat members:
1
2
Date today;
today.month = 1;//EROR today.month is a private field. 

Friend functions have access to all fields in class.
1
2
3
4
5
6
bool equal(const Date& left, const Date& right);
{
    return ( (left.year == right.year) && (left.month == right.month) && (left.day == right.day) );
    //previous statement wont cause error on left.year and similar
    //because it is an friend function
}

In some cases you have to use friend functions (i.e. overloading operator<< for outputting your data).

equal() function returns true if left argument equals to right. So if(equal(date1, date2)) means: "if dates are equal..."

It is better to overload operator== but looks like you didn't get to operator overloading yet.
Last edited on
Ok that makes more sense now. So would friend functions (in most cases) be a bad thing to use? Couldn't you usually just use an accessor instead of a friend function? I know there would be exceptions but I just mean in general.
So would friend functions (in most cases) be a bad thing to use?

You should try to limit the friend functions because they tend to break encapsulation.

Couldn't you usually just use an accessor instead of a friend function?

Usually yes. But sometimes you may not want to provide this access so some variable to any function except this special friend.
Thanks for clarifying that! One more quick question, is a static const basically the same as const but is used in classes and is available to all methods of that class and also all objects? Basically like a global variable? Or am I misunderstanding?
Yea you pretty much have it.
Topic archived. No new replies allowed.