Friend Function
A class contains:
👉Public
👉Private
👉Protected members
Public members- Accessed by all
Private members- Accessed by class members only
Protected members-Accessed by class members and its sub class(child class)
Without changing private mode if anywhere wants to access class members, friend function is an option.
Rules Friend Function Contains:
- It is a non-member function.
- It can access private, protected member of a class.
- Use friend keyword, in front of the function.
- Friend function has objects as arguments.
- Friend function should be called directly, without using objects.
Program:
#include<iostream.h>
class frndemo
{
int x,y;
public:
void setvalue()
{
x=10;
y=20;
}
friend void share(frndemo obj);
};
void share(frndemo obj)
{
cout<<\n"<<"x="<<obj.x;
cout<<\n"<<"y="<<obj.y;
}
void main()
{
frndemo obj;
obj.setvalue();
share(obj);
}