Home >>C++ Tutorial >C++ Friend Function

C++ Friend Function

Friend Function in C++

The class's private and protected data can be accessed by the use of a function, provided that the function is defined as a friend function in C++. The compiler in C++ gets to know that the provided function is a friend function just by the use of the keyword friend. Please note that in order to access the data the declaration of a friend function must be done in the body of a class that starts with the keyword friend.

Declaration of friend function in C++

Here is the syntax of the friend function in C++:

class class_name    
{    
    friend data_type function_name(argument/s);            // syntax of friend function.  
};    

In the above mentioned syntax or the declaration, it is depicted that the friend function is being preceded by the keyword friend. There is no boundation in the defining of the function, it can be defined anywhere in the program just like a normal C++ function. Please note that the definition of the function does not involve the use of either the keyword friend or scope resolution operator.

Characteristics of a Friend function

Here are the few characteristics of the friend function that is mentioned below:

  • The scope of the class does not contain functions and that is why it has been declared as a friend.
  • As the friend function is not in the scope of that class hence, it cannot be called by using the object.
  • The friend function can be invoked just like a normal function without the use of the object.
  • The member names cannot be accessed directly by the friend function and it has to be use an object name and dot membership operator with the member name in order to access the data.
  • Friend function in C++ can be declared either in the private or the public part.

C++ friend function Example

Here are the examples of the friend function in C++ that will clear your understanding about the subject:

#include <iostream>    
using namespace std;    
class Demo    
{    
    private:    
    int len;    
    public:    
	Demo(): len(0) { }    
	friend int printLen(Demo); //friend function    
};    
int printLen(Demo b)    
{    
   b.len += 100;    
    return b.len;    
}    
int main()    
{    
    Demo b;    
    cout<<"Box Length= "<< printLen(b)<<endl;    
    return 0;    
}   
Output :Box Length=100

C++ Friend class

A friend class in C++ can be accessed by both private and protected members of the class that has already been declared as a friend.

Here is an example of the friend class in C++ for your better understanding:

#include <iostream>    
using namespace std;  
class Demo  
{  
    int num =10;  
    friend class Test; //Declaration friend class.  
};  
class Test  
{  
  public:  
    void show(Demo &a)  
    {  
        cout<<"value of Num is : "<<a.num;  
    }  
};  
int main()  
{  
    Demo a;  
    Test b;  
    b.show(a);  
    return 0;  
}  
Output :value of Num is : 10

Popular Tutorials