Home | Projects | Notes > C++ Programming > Friends of a Class
Friend
A function or another class that has access to private class members
And, that function of or class is NOT a member of the class that it is accessing
Friends have unfettered access to both public and private data members of a class, but they're not members of the class.
Friend functions
Can be regular non-member standalone functions
Can be member methods of another class
Friend class
Another class can have access to private class members
The entire class will have access to the private information of the class granting friendship.
Friendship must be granted, NOT taken!
A class must explicitly declare its friends in its class declaration using the friend
keyword.
Friendship is not symmetric
Must be explicitly granted
A being a friend of B does not necessarily make B a friend of A
Friendship is not transitive
Must be explicitly granted
A being a friend of B, and B being a friend of C, does not necessarily make A a friend of C
Friendship is NOT inherited
Non-member function as a friend
xxxxxxxxxx
161class Player
2{
3 friend void display_player(Player &p); // Non-member standalone function
4 std::string name;
5 int health;
6 int xp;
7public:
8 . . .
9};
10
11void display_player(Plyaer &p)
12{
13 std::cout << p.name << std::endl;
14 std::cout << p.health << std::endl;
15 std::cout << p.xp << std::endl;
16}
The
Player
class grants the friendship.Since
display_player()
is a friend function of the classPlayer
, it can modify thePlayer
's private data members. (It doesn't not have to use public getters/setters to access or modify thePlayer
's private data.)
Member function of another class as a friend
xxxxxxxxxx
211class Player
2{
3 friend void Other_class::display_player(Player &p); // Member of another class
4 std::string name;
5 int health;
6 int xp;
7public:
8 . . .
9}
10
11class Other_class
12{
13 ...
14public:
15 void display_player(Player &p)
16 {
17 std::cout << p.name << std::endl;
18 std::cout << p.health << std::endl;
19 std::cout << p.xp << std::endl;
20 }
21};
display_player()
method ofOther_class
will now have access to everything in thePlyaer
class.
Another class as a friend
xxxxxxxxxx
91class Player
2{
3 friend class Other_class; // Another class
4 std::string name;
5 int health;
6 int xp;
7public:
8 . . .
9};
All the methods in the
Other_class
will have access to thePlayer
class' private attributes.
Sometimes we have classes that use other classes and writing code using getters/setters becomes long tedious and sometimes gives you overhead. However that shouldn't be the only reason for granting friendship. Friendships should be granted only when it makes sens in the design of your system, and then only the minimal necessary friendship should be granted.