Definition of Friend Function
The friend function is used to access the private and protected members of a class by permitting the non-member function to gain access. In this type of function, a friend keyword is used before the function name at the time of declaration. There are some restrictive conditions applied to friend function. The first condition is that friend function is not inherited by a child class. The second condition is that storage class specifier may not be present in friend function, which means that it can not be declared as static and extern.
The friend function is not called with an invoking object of the class. The examples of friend function are: a global function, member function of a class, function template can be a friend function. Let’s understand it with the help of an example.
- #include <iostream>
- using namespace std;
- class first
- {
- int data;
- public:
- first (int i):data(i){}
- friend void display (const first& a);
- };
- void display (const first& a)
- {
- cout<<"data = "<<a.data;
- }
- int main()
- {
- first obj(10);
- display (obj);
- return 0;
- }
- //Output
- data = 10
No comments:
Post a Comment