Protected and private members of a class cannot be accessed from outside the class in which they are declared. A friend class can access these members of another class in which it is declared as friend.Friend declaration can appear in any section i.e public,protected or private.A friend declaration specified in protected section does not prevent the friend from accessing private fields of a class.
PROGRAM TO EXPLAIN FRIEND CLASS IN C++
using namespace std;
private: int a;
friend class Test1; // Friend Class
void showTest(Test& x)
// Since Test1 is friend of Test, it can access
// private members of Test
std::cout << "Test::a=" << x.a<<"\n";
Points about friend classes:-
1)The value of Encapsulation of classes in object oriented programming lessens if too many classes are declared as friend,so friend keyword should be used for limited purpose.
2)If Class A is a friend of Class B then it does not mean that class B is friend of Class A i.e Friendship is not mutual.
3) If class B inherits class A and Class C is friend of Class A then it does not mean that Class C will be friend of Class B i.e Friendship is not inherited .