FRIEND FUNCTION IN C++ WITH EXAMPLE - DEEP CODER

Breaking

printf("Learn Deep Coding Here!!");

FRIEND FUNCTION IN C++ WITH EXAMPLE

Definition of Friend Function

The friend function is used to access the private and protected members of a class by permitting the non-member function to gain access. In this type of function, a friend keyword is used before the function name at the time of declaration. There are some restrictive conditions applied to friend function. The first condition is that friend function is not inherited by a child class. The second condition is that storage class specifier may not be present in friend function, which means that it can not be declared as static and extern.
The friend function is not called with an invoking object of the class. The examples of friend function are: a global function, member function of a class, function template can be a friend function. Let’s understand it with the help of an example.
  1. #include <iostream>
  2. using namespace std;
  3. class first
  4. {
  5. int data;
  6. public:
  7. first (int i):data(i){}
  8. friend void display (const first& a);
  9. };
  10. void display (const first& a)
  11. {
  12. cout<<"data = "<<a.data;
  13. }
  14. int main()
  15. {
  16. first obj(10);
  17. display (obj);
  18. return 0;
  19. }
  20. //Output
  21. data = 10

The following properties explain the concept of Friend Function clearly;

  1. Friend function is not a member function of a class to which it is a friend.
  2. Declare in class with "Friend " keyword.
  3. It must be define outside the class but declare inside the class.
  4. It can not access member of the class directly.
  5. It has no caller Object.
  6. It should not be define with membership label.  


No comments:

Post a Comment