Friend function acts as a friend of the class. It can access the private and protected members of the class. The friend function is not a member of the class, but it must be listed in the class definition. The non-member function cannot access the private data of the class. Sometimes, it is necessary for the non-member function to access the data. The friend function is a non-member function and has the ability to access the private data of the class.
To make an outside function friendly to the class, we need to declare the function as a friend of the class as shown below:
class sample { // data members; public: friend void abc(void); };
Let's understand this through an example:
#include <iostream> using namespace std; class Addition { int a=5; int b=6; public: friend int add(Addition a1) { return(a1.a+a1.b); } }; int main() { int result; Addition a1; result=add(a1); cout<Output:return 0; }
11
If you like dEexams.com and would like to contribute, you can write your article here or mail your article to admin@deexams.com . See your article appearing on the dEexams.com main page and help others to learn.