Search Your Topic

config
Thursday, 15 June 2017 06:15

C++ friend function

Written by
Rate this item
(0 votes)

If a function is defined as a friend function in C++ then the protected and private data of a class can be accessed using the function.

By using the keyword friend compiler knows the given function is a friend function.

For accessing the data, the declaration of a friend function should be done inside the body of a class starting with the keyword friend.


Declaration of friend function in C++

 
  1. class class_name  
  2. {  
  3.     friend data_type function_name(argument/s);  
  4. };  

C++ friend function Example

Let's see the simple example of C++ friend function used to print the length of a box.

 
  1. #include <iostream>  
  2. using namespace std;  
  3. class Box  
  4. {  
  5.     private:  
  6.         int length;  
  7.     public:  
  8.         Box(): length(0) { }  
  9.         friend int printLength(Box); //friend function  
  10. };  
  11. int printLength(Box b)  
  12. {  
  13.     b.length += 10;  
  14.     return b.length;  
  15. }  
  16. int main()  
  17. {  
  18.     Box b;  
  19.     cout<<"Length of box: "<< printLength(b)<<endl;  
  20.     return 0;  
  21. }  

Output:

Length of box: 10  

 

Read 30 times
Anish Sir

"I am delighted once again to pen the welcome note to the Tosh!Yas Technologies ."

 Call +91 74 88 34 7779  | Email : anishsingh@live.com

toshiyas.in
More in this category: « C++ Enumeration C++ Inheritance »

Leave a comment

Make sure you enter all the required information, indicated by an asterisk (*). HTML code is not allowed.