blog
blog copied to clipboard
C++ Friends of Classes
Concept: A
friend
is a function or class that is not a member of a class, but has access to the private members of the class.
- Friend function: a function that is not a member of a class, but has access to private members of the class.
- A friend function can be a stand-alone function or a member function of another class.
- It is declared a friend of a class with the
friend
keyword in the function prototype.
// A friend function as a stand-alone function.
class MyClass
{
private:
int x;
friend void fSet(MyClass &c, int a);
};
void fSet(MyClass &c, int a)
{
c.x = a;
}
// A friend function as a member of another class.
class MyClass
{
private:
int x;
friend void OtherClass::fSet(myClass &c, int a);
};
class OtherClass
{
public:
void fSet(myClass &c, int a)
{
c.x = a;
}
}
// An entire class can be declared a friend of a class.
class MyClass
{
private:
int x;
friend class FriendClass;
};
class FriendClass
{
public:
void fSet(MyClass &c, int a)
{
c.x = a;
}
int fGet(MyClass c)
{
return c.x;
}
};
If FriendClass
is a friend of MyClass
, then all member functions of FriendClass
have unrestricted access to all private members of MyClass
.
In general, you should restrict the property of Friendship to only those functions that must have access to the private members of a class.