The main concept of the object oriented programming are data hiding and data encapsulation. Whenever data variables are declared in a private category of a class these members are restricted from accessing by non-member functions.
To access a private data member by a non-member function is to change a private data member to a public group. When the private or protected data member is changed to a public category, it violates the whole concept of data hiding and data encapsulation. To solve this problem, a friend function can be declared to have access to these data members. Friend is a special mechanism for letting non-member functions access private data. A friend function may be declared or defined within the scope of a
class definition.
The keyword friend inform the compiler that it is not a member function of the class.
The general form is
friend return_type user_function_name(parameters);
where friend is a keyword used as function modifier.
Example:
class alpha
{
private:
int x;
public:
void getdata( );
friend void display (alpha abc);
{
cout<<"value of x = "<<abc.x;
cout<< endl;
}
};
void sample :: getdata ( )
{
cout<<"enter value for x \n";
cin>>x;
}
void main ( )
{
alpha a;
a.getdata ( );
cout<<"accessing private data by non-member function"<<endl;
display(a);
}
0 Comments