Friend Function in C++ - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Community

demo-image

Friend Function in C++

Share This

It is possible to grant a nonmember function access to the private members of a class by using a friend. A friend function has access to all private and protected members of the class for which it is a friend.


Here, the function sum is not a member function of class Test . Still, it can access private member of class Test as it's a friend function of the class.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
using namespace std;
class Test {
int x, y;
public:
friend int sum(Test t);
void setValues(int x, int y) {
this -> x = x;
this -> y = y;
}
};
int sum (Test t) {
return t.x + t.y;
}
int main() {
Test t;
t.setValues(4, 5);
cout << sum(t) << endl;
return 0;
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX




Happy Exploring!

Comment Using!!

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.