A friend of a class is a function or class that is
given permission to name the private and protected members of the class
. A class specifies its friends, if any, by way of friend declarations
. Such declarations give special access rights to the friends, but they
do not make the nominated friends members of the befriending class
. [
Example 1:
The following example illustrates the differences between
members and friends:
class X {
int a;
friend void friend_set(X*, int);
public:
void member_set(int);
};
void friend_set(X* p, int i) { p->a = i; }
void X::member_set(int i) { a = i; }
void f() {
X obj;
friend_set(&obj,10);
obj.member_set(10);
}
—
end example]