Friend functions in C++


In C++ a function or an entire class may be declared to be a friend of another class or function. Friend function can also be used for overloading functions.

The declaration of friend function can appear anywhere in the class. But a good practice would be where the class ends. An ordinary function that is not the member function of a class has no privilege to access the private data members, but the friend function does have the capability to access any private data members. If you look at the program friend.cpp, it is not a member of the class but has an access to the non-public members of the class. The declaration of the friend function is very simple. The keyword friend in the class prototype inside the class definition precedes it. In the example program friend.cpp, the function mul() is declared as friend function of class frd.

Friend Function Program Example

  1. //program name: friend.cpp
  2. #include
  3. #include
  4. class frd
  5. {
  6.             private:
  7.             int a, b;
  8.             public:
  9.             frd():a(10), b(40)
  10. { }
  11. int add()
  12. {
  13.             return(a+b);
  14. }
  15. friend int mul(frd);
  16. };
  17. int mul(frd x)
  18. {
  19. return (x.a *x.b);
  20. }
  21. int main (void)
  22. {
  23. clrscr();
  24. class frd friend;
  25. cout<
  26. cout<
  27. return(0);
  28. }

Run output



In C++, friend means to give permission to a class or function. The non-member function has to grant an access to update or access the class.

The advantage of encapsulation and data hiding is that a non-member function of the class cannot access a member data of that class. Care must be taken using friend function because it breaks the natural encapsulation, which is one of the advantages of object oriented programming. It is best used in the operator overloading.

It seems that member functions and friend functions are equally privileged. But if you look closely to see the difference is that a friend function in the program friend.cpp is called like mul(frd), while a member function is called like friend.add(). The advantage of friend function is that it provides freedom. It is up to the programmer to choose which one would be more readable and flexible for future modification and also the consideration of maintenance cost must be taken into account. But look at the other side of friend functions, the major disadvantage is that they require an extra line of code when you want dynamic binding.

Learn more about Functions in C++ and the different types of functions in C++

Exit mobile version