Here is an example:
1 2 3 4 5 6 7 8 9 10 11 12
|
class Foo {
public :
Foo() : x() {}
private :
int x;
friend void set_x_to_one(Foo&);
};
void set_x_to_one(Foo& foo) {
foo.x = { 1 };
}
|
Notice that the function 'set_x_to_one' is not a member function of 'Foo', it is a friend function. A friend function is one that has access to a class' private members (in this case 'x') and doesn't belong to said class.
This is done by declaring the function inside the class with the
friend
keyword (line 7).
It does not matter under which access specification (public, private, protected) you place the declaration - in my example I've elected to place it under the 'private' keyword, but I could have made it public -
it makes no difference.
The actual function definition goes outside of the class (line 10). Notice how we didn't use the scope resolution operator (::) since the function doesn't belong to any class.
Finally, line 11 of my example is why we made the function a
friend
in the first place. I would not be able to access object foo's 'x' member variable like this because it is private, unless I had a getter or something similar. If you comment-out line 7 of my example, you will see that your compiler will give you an error (or your IDE will highlight it for you) on line 11 because suddenly 'set_x_to_one' is just a global function, and does not have access to 'x'.