Introduction

In this blog, we will learn about friend function in the C++ language. In object oriented programming language private members cannot access from outside the class. In this situation friend function plays a major role.

What is friend function?

A function that accesses private members of a class but is not itself a member of class is called friend function.

Characteristics of a friend function

  • It is not declared as a member of any class.
  • It is invoked like a normal function using the friend keyword.
  • It can access the private members of a class using the object name.
  • It has the objects as arguments.

Example

This example shows how to access private members of a class using the friend function.

  1. // sum of two numbers using the friend function
  2. #include<iostream.h>
  3. #include<conio.h>
  4. class B; //declre class b
  5. class A
  6. {
  7. private:
  8. int a; // private data
  9. public:
  10. void setData() // member function
  11. {
  12. cout<<"Enter 1st number: ";
  13. cin>>a;
  14. }
  15. friend void sum(A ob1,B ob2); //declare friend function
  16. };
  17. class B
  18. {
  19. private:
  20. int b; //private data
  21. public:
  22. void setData() // member function
  23. {
  24. cout<<"Enter 2nd number: ";
  25. cin>>b;
  26. }
  27. friend void sum(A ob1,B ob2); // declare friend function
  28. };
  29. void sum(A ob1,B ob2)
  30. {
  31. int s=ob1.a+ob2.b; //accessing private data
  32. cout<<"sum: "<<s<<endl;
  33. }
  34. void main()
  35. {
  36. clrscr();
  37. A obj1;
  38. B obj2;
  39. obj1.setData();
  40. obj2.setData();
  41. sum(obj1,obj2); //invoking the friend function
  42. getch();
  43. }

Friend Function In C++

In this blog, I will try to explain how to access private data of a class using the friend function in C++ language. Thanks for reading.