Advertisement

Friend Function in C++ | Mohd Abuzar

Through this video we are learning about friend function in c++




Function is defined as a friend function  in c++  , then the private and protected data member can be accessed using the function .


By using this keyword compiler knows that this is friend function 



Characteristic of Friend function in c++ 

  • The function is not in the scope which is declared as friend function 
  • It is not called using the object 
  • It can be Invoked like normal function without using the object 
  • It can not accessed the member name directly 
  • It is accessed by function name dot member operator with the member name
  • It can declared in private , protected or public function.      


  C++ friend function Example  

  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


In the above Code you will see that what is friend function and how friend function works.



This article is Contributed by Mohd Abuzar . If you like Code with abuzar  or want to give 

more suggestion or write something you can mail at abuzar.abuzar.mohd325@gmail.com


Please write comment if you find anything incorrect .




Post a Comment

0 Comments