Friends

A friend of a class allow access to the private members of that class, because there are some cases where this is required when the whole of the created class is required to be viewable, e.g. when a private member is not being able to set with the class methods.

To declare a friend within a class, for example to declare a function / class as a friend.

friend int FuncToFriendClass(int a);              // friend to the function.
friend class ClassToClassFriend;              // friend to a class

This will allow the function FuncToFriendClass to gain access to all objects within the class, and the class ClassToClassFriend as well.

The source code

int FuncToFriendClass(int a);              // declare the function, for the class to make a friend.
 
class FriendlyClass 
{
private:
       int private_data;
 
       friend int FuncToFriendClass(int a);              // friend to the function.
       friend class ClassToClassFriend;              // friend to a class
public:
       FriendlyClass()
       {
              private_data = 5;
       }
};
 
int FuncToFriendClass(int a)
{
       FriendlyClass friendClass;                            // the friend to this funciton.
       return friendClass.private_data + a;
}
 
class ClassToClassFriend
{
public:
       int FriendClassPrivateDataMinus(int b)
       {
              FriendlyClass classFriend;
              return classFriend.private_data - b;
       }
};
 
int main()
{
       ClassToClassFriend classFriend;
       std::cout << "Friendly function to class =" << FuncToFriendClass(3) << "\n";
       std::cout << "Friendly class to class = " << classFriend.FriendClassPrivateDataMinus(2) << "\n";
       return 0;
}

If you save that as friend.cpp and then compile, the output will be
Friendly function to class = 8
Friendly class to class = 3

Leave a Reply

Your email address will not be published.