Skip to content
Related Articles

Related Articles

Friend class and function in C++

View Discussion
Improve Article
Save Article
Like Article
  • Difficulty Level : Medium
  • Last Updated : 12 Jun, 2022
 

Friend Class A friend class can access private and protected members of other class in which it is declared as friend. It is sometimes useful to allow a particular class to access private members of other class. For example, a LinkedList class may be allowed to access private members of Node. 

A friend class can access both private and protected members of the class in which it has been declared as friend.
 

CPP




class Node {
private:
    int key;
    Node* next;
    /* Other members of Node Class */
 
    // Now class  LinkedList can
    // access private members of Node
    friend class LinkedList;
};

 

C++




// Example:
 
#include<iostream>
using namespace std;
 
class A
{
    int x;
          public:
             
    A()
    {
        x=10;
    }
    friend class B;    //friend class
};
 
class B
{
    public:
        void display(A &t)
        {
            cout<<endl<<"The value of x="<<t.x;
        }   
};
 
main()
{
    A _a;
    B _b;
    _b.display(_a);
    return 0;
}

Output

The value of x=10
In this example, class B is declared as a friend inside the class A. Therefore, B is a friend of class A. 
Class B can access the private members of class A.

Friend Function Like friend class, a friend function can be given a special grant to access private and protected members. A friend function can be: 
a) A member of another class 
b) A global function 
 

  •  A friend function is a special function in C++ which in-spite of not being member function of a class has privilege to access private and protected data of a class.
  • A friend function is a non member function or ordinary function of a class, which is declared as a friend using the keyword “friend” inside the class. By declaring a function as a friend, all the access permissions are given to the function.
  • The keyword “friend” is placed only in the function declaration of the friend function and not in the function definition.
  • When friend function is called neither name of object nor dot operator is used. However it may accept the object as argument whose value it want to access.
  • Friend function can be declared in any section of the class i.e. public or private or protected.

Syntax:- 

Syntax :

class <class_name>    
{    
    friend  <return_type>  <function_name>(argument/s);  
};

C++




// Example: Find the largest of two numbers using Friend Function
 
#include<iostream>
using namespace std;
 
class Largest
{
    int a,b,m;
    public:
        void set_data();
        friend void find_max(Largest);       
};
 
void Largest::set_data()
{
    cout<<"Enter the First No:";
    cin>>a;
    cout<<"Enter the Second No:";
    cin>>b;
}
 
 
 
void find_max(Largest t)
{
    if(t.a>t.b)
        t.m=t.a;
    else
        t.m=t.b;
         
        cout<<"Maximum Number is\t"<<t.m;
}
 
main()
{
    Largest l;
    l.set_data();
    find_max(l);
    return 0;
}

Output

Enter the First No:Enter the Second No:Maximum Number is    0

Output:-

Enter the First No: 21
Enter the Second No:32
Maximum Number is    32

Friend Function to more than one classes / A Function Friendly to two classes:-

C++




// Prog: Demonstrates how friend functions work as a bridge between the classes
 
#include<iostream>
using namespace std;
 
class ABC;// forward declaration
 
class XYZ
{
    int x;
    public:
        void set_data(int a)
        {
            x=a;
        }
         
        friend void max(XYZ,ABC);
};
 
 
class ABC
{
    int y;
    public:
        void set_data(int a)
        {
            y=a;   
        }    
         
    friend void max(XYZ,ABC);
};
 
void max(XYZ t1,ABC t2)
{
    if(t1.x>t2.y)
        cout<<t1.x;
    else
        cout<<t2.y;
}
 
main()
{
    ABC _abc;
    XYZ _xyz;
    _xyz.set_data(20);
    _abc.set_data(35);
     
    max(_xyz,_abc);  //callin friend function
    return 0;
}

Output

35

CPP




class Node {
private:
    int key;
    Node* next;
 
    /* Other members of Node Class */
    friend int LinkedList::search();
    // Only search() of linkedList
    // can access internal members
};

Following are some important points about friend functions and classes: 
1) Friends should be used only for limited purpose. too many functions or external classes are declared as friends of a class with protected or private data, it lessens the value of encapsulation of separate classes in object-oriented programming.
2) Friendship is not mutual. If class A is a friend of B, then B doesn’t become a friend of A automatically.
3) Friendship is not inherited (See this for more details)
4) The concept of friends is not there in Java. 
A simple and complete C++ program to demonstrate friend Class 
 

CPP




#include <iostream>
class A {
private:
    int a;
 
public:
    A() { a = 0; }
    friend class B; // Friend Class
};
 
class B {
private:
    int b;
 
public:
    void showA(A& x)
    {
        // Since B is friend of A, it can access
        // private members of A
        std::cout << "A::a=" << x.a;
    }
};
 
int main()
{
    A a;
    B b;
    b.showA(a);
    return 0;
}

Output

A::a=0

A simple and complete C++ program to demonstrate friend function of another class 
 

CPP




#include <iostream>
 
class B;
 
class A {
public:
    void showB(B&);
};
 
class B {
private:
    int b;
 
public:
    B() { b = 0; }
    friend void A::showB(B& x); // Friend function
};
 
void A::showB(B& x)
{
    // Since showB() is friend of B, it can
    // access private members of B
    std::cout << "B::b = " << x.b;
}
 
int main()
{
    A a;
    B x;
    a.showB(x);
    return 0;
}

Output

B::b = 0

A simple and complete C++ program to demonstrate global friend 
 

CPP




#include <iostream>
 
class A {
    int a;
 
public:
    A() { a = 0; }
 
    // global friend function
    friend void showA(A&);
};
 
void showA(A& x)
{
    // Since showA() is a friend, it can access
    // private members of A
    std::cout << "A::a=" << x.a;
}
 
int main()
{
    A a;
    showA(a);
    return 0;
}

Output

A::a=0

Merits:-

  •  A friend function is able to access members without the need of inheriting the class.
  • Friend function acts as a bridge between two classes by accessing their private data.
  • It can be used to increase the versatility of overloaded operator.
  • It can be declared either in the public or private or protected part of class.

Demerits:-

  • Friend functions have access to private members of a class from outside the class which violates the law of the data hiding.
  • Friend functions cannot do any run time polymorphism in its members.
     

References: 
http://en.wikipedia.org/wiki/Friend_class 
http://en.wikipedia.org/wiki/Friend_function 
http://www.cprogramming.com/tutorial/friends.html 
http://www.parashift.com/c++-faq/friends-and-encap.html
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
 


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!