Friend Function in C++
Friend Function in C++
A friend function in C++ is defined as outside that class and it has the right to access all private members and protected members of the class.
A friend function define as a function of the class defined outside the class scope and if a function is defined as a friend function then, the private and protected data of class.
Friend function is declared by using friend keyword.
Syntax of friend function
class className { ... .. ... friend returnType functionName(arguments); ... .. ... }
Program of friend function
#include <iostream> using namespace std; class Box { private: int length; public: Box(): length(0) { } friend int printLength(Box); }; int printLength(Box b) { b.length += 10; return b.length; } int main() { Box b; cout<<"Length of box: "<< printLength(b)<<endl; return 0; }
Output
Length of box: 10
Read more, Inheritance types in C++