Friend function in C++: Uses and limitations

Friend function is used to provide access to a non member function for accessing private members of a class. A friend function has access to all private as well as protected members of a class.

For Example:

class test {

int i, j;


friend int add(myclass a);

void set_ij(int x, int y);


Here add() is the friend function.

Uses of friend functions:

1) It is used to create many input/output functions.

2) Friend function is used for operator overloading.

3) It is useful when members of a class are interrelated to other sections of the program.

4) It is used to create effective code.

Limitations of a friend function:

1) It doesn’t have a storage class specifier.

2) A derived class can’t inherit friend functions.

Leave a Reply