Professional Documents
Culture Documents
Friend Function and Friend Class in C++
Friend Function and Friend Class in C++
in C++
Friend Function
• Generally, non-member functions
– Cannot access the private members of a particular class
• A friend function is
– A function that is declared outside a class but is capable of
accessing the private and protected members of the class
– May be
• A global function
• A member of another class
When we need a Friend Function?
– There could be situations in programming wherein
• Two classes may want to share their members which may be
data members, member functions or function templates
class B return 0;
{ }
private:
int x;
public:
B() Output:
{
x = 4; Value of x = 4
}
friend void A::display(B);
};
Implementing Friend Class
• A friend class is used
– When a class needs to access private and protected members of
another class
– Syntax-
class A
{
//Other declarations
friend class B;
};
class B
{
};
Implementing Friend class
#include <iostream> class B
{
using namespace std; public:
void print(A &a1)
class A {
{ cout << "\n Value of x = " << a1.x << endl;
private: }
};
int x;
int main()
public: {
A() A a;
{ B b;
x = 5; b.print(a);
}
friend class B; return 0;
}; }
Output:
Value of x = 5
some important points about friend functions
and classes
• Friends should be used only for limited purpose
– Too many functions or external classes are declared as friends of
a class, it lessens the value of encapsulation in object-oriented
programming
– Friendship is not mutual
• If class A is a friend of B, then B doesn’t become a friend of A
automatically
• Friendship is not inherited