A friend function, that is a "friend" of a given class, is a function that is given the same access as methods to private and protected data. A friend function is declared by the class that is granting access, so friend functions are part of the class interface, like methods.
example of friend function:-
#include <iostream>
using namespace std;
class A{
private:
int a;
public:
void disp(int x){
a=x;
cout<<a<<endl;
}
friend int modify(A);
};
int modify(A aObj){
aObj.a=aObj.a+7;
return aObj.a;
}
int main(){
A obj;
obj.disp(5);
cout<<modify(obj);
}
example of friend function:-
#include <iostream>
using namespace std;
class A{
private:
int a;
public:
void disp(int x){
a=x;
cout<<a<<endl;
}
friend int modify(A);
};
int modify(A aObj){
aObj.a=aObj.a+7;
return aObj.a;
}
int main(){
A obj;
obj.disp(5);
cout<<modify(obj);
}