top of page
Friend function

 

Remember that a member which is not public (private and protectedcan not be accessed from outside the class. 

 

There are some situations where you may need to access these members outside the class. Keyword friend  is used for this purpose.

 

Friend functions and friend classes can access all the members of a class. 

 

This concept is controversial. People say friend concept violates data encapsulation.

 

A friend function is a non-member function but still can access all the members of a class including private members.

 

To make an outside function as friend to a class, it has to be declared within class body with the prefix "friend".

printNum() is not member of class Number. But it can still access all members including private members (num), because it is a friend function.

A member of another class can be friend of a class.

e.g.


 

Here the function print() from class B, is able to access private member of A as it is declared as a friend function. Notice the forward declaration of class A, before it is used as a parameter to print() in class B.

Friend class

A class can be declared as a friend of another class.

e.g.

Output
10

 

ob1 - is an object of A class.

 

So it should not be able to access private members of Number class. But as A class is declared as a friend of Number class. So printNumber() and getNumber() functions of A class can access private data num of Number class.

 

Note:

  • Friend declaration is not transitive - if class A is declared a friend of class B, this does not make class B a friend of class A.

  • Friend status is not inherited - in the above example the derived class of A can't access the members of class B.

bottom of page