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
1 2 3 4 5 6 7 8 9 10 |
class className{ ...... friend retyrn_type function_Name(argument); ....... } return_type function_Name(argument){ ...... } |
C++ friend function Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
#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; } |
Output:
1 2 3 |
Length: 15 |
C++ friend function in two different class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
#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; } |
Output:
1 2 3 |
Sum: 15 |