Friend functions are those function that is not a member of class. It also define the outside of class. Using friend function you can access the private and protected member of a class. Friend function declare within the class and define outside of the class. It is special type of function.
How to declare Friend Function:
For declaring friend function you can use friend keyword.
Syntax :
//within class declaration class className { friend functionName( parameters ); }
Advantage of Friend Function:
- Friend functions can access private and protected members of a class.
- The most powerful advantage of encapsulation and data hiding is that a non-member function of the class it cannot access a member data of that particular class.
- It is very helpful for operator overloading.
Find the square of a number using friend function:
#include<iostream> using namespace std; Class SquareExample { int number; public: void enterNumber() { cout<<”Enter Any Number… “; cin>>number; } friend int findSquare(SquareExample obj1); };
int findSquare(SquareExample obj1) { return (obj1.number*obj1.number); } int main() { SquareExample obj; obj.enterNumber(); cout<< “Square of a number is : ”<< findSquare(obj); return 0; }