Home >>C++ Tutorial >C++ Friend Function
The class's private and protected data can be accessed by the use of a function, provided that the function is defined as a friend function in C++. The compiler in C++ gets to know that the provided function is a friend function just by the use of the keyword friend. Please note that in order to access the data the declaration of a friend function must be done in the body of a class that starts with the keyword friend.
Here is the syntax of the friend function in C++:
class class_name { friend data_type function_name(argument/s); // syntax of friend function. };
In the above mentioned syntax or the declaration, it is depicted that the friend function is being preceded by the keyword friend. There is no boundation in the defining of the function, it can be defined anywhere in the program just like a normal C++ function. Please note that the definition of the function does not involve the use of either the keyword friend or scope resolution operator.
Here are the few characteristics of the friend function that is mentioned below:
Here are the examples of the friend function in C++ that will clear your understanding about the subject:
#include <iostream> using namespace std; class Demo { private: int len; public: Demo(): len(0) { } friend int printLen(Demo); //friend function }; int printLen(Demo b) { b.len += 100; return b.len; } int main() { Demo b; cout<<"Box Length= "<< printLen(b)<<endl; return 0; }
A friend class in C++ can be accessed by both private and protected members of the class that has already been declared as a friend.
Here is an example of the friend class in C++ for your better understanding:
#include <iostream> using namespace std; class Demo { int num =10; friend class Test; //Declaration friend class. }; class Test { public: void show(Demo &a) { cout<<"value of Num is : "<<a.num; } }; int main() { Demo a; Test b; b.show(a); return 0; }