C++ Friend function
A friend function has the right to access all private and protected members of a class although it is defined outside that class' scope. Syntax
class className{
......
friend retyrn_type function_Name(argument);
.......
}
return_type function_Name(argument){
......
}
C++ friend function Example
#include <iostream>
using namespace std;
class Length
{
private:
int meter;
public:
Length(): meter(5) { }
friend int addMethod(Length); //friend function declaration
};
int addMethod(Length l) // friend function definition
{
l.meter += 10; //accessing private data from non-member function
return l.meter;
}
int main()
{
Length L;
int totallength;
totallength=addMethod(L);
cout<<"Length: "<< totallength;
return 0;
}
Length: 15
C++ friend function in two different class
#include <iostream>
using namespace std;
class B;// forward declaration
class A {
private:
int numA;
public:
A(): numA(5) { }
friend int add(A, B); // friend function declaration
};
class B {
private:
int numB;
public:
B(): numB(10) { }
friend int add(A , B); // friend function declaration
};
// Function add() is the friend function of classes A and B
// that accesses the member variables numA and numB
int add(A objectA, B objectB)
{
return (objectA.numA + objectB.numB);
}
int main()
{
A objectA;
B objectB;
cout<<"Sum: "<< add(objectA, objectB);
return 0;
}
Sum: 15