We know private members can not be accessed from outside the class. That is a non – member function can’t have an access to the private data of a class.
In such situations, c++ allows the common function lo be made friendly with both the classes , there by following the function to have access to the private data of these classes .Such a function need not be a member of any of these classes.
A class can grant any function a special permit for direct access to its private members. This is achieved by declaring the function as a friend. The friend keyword must precede the function prototype in the class definition.
What is Friend Function ?
A friend function is a function which is declared within a class and is defined outside the class. It does not require any scope resolution operator for defining. It can access private members of a class. It is declared by using keyword “friend”
Syntax:
class ABC
{
---------
---------
public:
--------
----------
friend void xyz(void);
};
Characteristics of Friend Function:
- It can be declared either in the public or private part of a class without affecting its meaning.
- A friend function, as though not a member function , has full access rights to the private members of the class.
- It is not in the scope of the class to which it has been declared as friend.
- Since it is not in the scope of the class, it cannot be called using the object of that class.
- It can be invoked like a member function without the help of any object.
- Unlike member functions, it cannot access the member names directly and has to use an object name and dot membership operator with each member name.
- Usually, it has the objects as arguments.
Example: To find max of two numbers using friend function for two different classes.
#include<iostream>
using namespace std;
class sample2;
class sample1
{
int x;
public:
sample1(int a)
{
x=a;
}
friend void max(sample1 s1,sample2 s2);
};
class sample2
{
int y;
public:
sample2(int b)
{
y=b;
}
friend void max(sample1 s1,sample2 s2);
};
void max(sample1 s1,sample2 s2)
{
if(s1.x > s2.y)
cout<<”Data member of class sample1 is larger";
else
cout<<”Data member of class sample2 is larger";
}
void main()
{
sample1 obj1(3);
sample2 obj2(5);
max(obj1,obj2);
}
You must log in to post a comment.