Friend Function
C++ Friend function
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); // syntax of friend
function.
4. };
In the above declaration, the friend function is preceded by the keyword friend.
The function can be defined anywhere in the program like a normal C++
function. The function definition does not use either the keyword friend or
scope resolution operator.
Characteristics of a Friend function:
 The function is not in the scope of the class to which it has been
declared as a friend.
 It cannot be called using the object as it is not in the scope of that
class.
 It can be invoked like a normal function without using the object.
It cannot access the member names directly and has to use an
object name and dot membership operator with the member name.
It can be declared either in the private or the public part.
C++ friend function Example
#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. };
C++ friend function Example
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
C++ friend function Example 2
1. #include <iostream>
2. using namespace std;
3. class B; // forward
declarartion.
4. class A
5. {
6. int x;
7. public:
8. void setdata(int i) {
10. x=i;
11. }
{
10. x=i;
11. }
C++ friend function Example 2
12. friend void min(A,B); // friend function.
13. };
14. class B
15. {
16. int y;
17. public:
18. void setdata(int i)
19. {
20. y=i;
21. }
22. friend void min(A,B); // friend function
23. };
24. void min(A a,B b)
25. {
26. if(a.x<=b.y)
27. std::cout << a.x << std::endl;
28. else
29. std::cout << b.y << std::endl;
30. }
C++ friend function Example 2
31. int main()
32. {
33. A a;
34. B b;
35. a.setdata(10);
36. b.setdata(20);
37. min(a,b);
38. return 0;
39. }
Output:
10
C++ Friend class
A friend class can access both private and protected members of the
class in which it has been declared as friend.
Example of a friend class.
1. #include <iostream>
2.
3. using namespace std;
4.
5. class A
6. {
7. int x =5;
8. friend class B; // friend class.
9. };
10. class B
11. {
12. public:
13. void display(A &a)
14. {
15. cout<<"value of x is : "<<a.x;
16. }
17. };
Example of a friend class.
18. int main()
19. {
20. A a;
21. B b;
22. b.display(a);
23. return 0;
24. }
Output:
value of x is : 5