Friend class in C++
Friend class
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++
#include <iostream>
using namespace std;
class Test
{
private: int a;
public:
Test()
{
a=0;
}
friend class Test1; // Friend Class
};
class Test1
{
private:
int b;
public:
void showTest(Test& x)
{
// Since Test1 is friend of Test, it can access
// private members of Test
std::cout << "Test::a=" << x.a<<"\n";
}
};
int main()
{
Test a;
Test1 b;
b.showTest(a);
return 0;
}
OUTPUT:
Test::a=0
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 .
0 Comment(s)