Friend Function in C++ - BunksAllowed

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

Community

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.


#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; }




Happy Exploring!

No comments:

Post a Comment

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