### 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:

 ``12345678`` ``````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!
 ``12`` ``````Date today; today.month = 1;//EROR today.month is a private field. ``````

 ``123456`` ``````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 }``````

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

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.