What is a friend function?
Private data members cannot be accessed from outside the class. However, situations arise where two classes need to share a particular function. For such situations, C++ introduces friend functions. These are functions that can be made friendly with both the classes, thus allowing these functions to have an access to the private data of these classes.
What are friend functions?
- To allow a non-member function the access to private members of a class, it needs to be friend of that class. Friend functions can access private and protected data of the class. To make a non-member function friend of a class, its declaration needs to be made inside the class and it has to be preceded by the keyword friend. We can also have a member function of a class to be friend of certain other class. Even if a function is not a member of any class, it can still be friend of multiple classes.
- If we write equivalent friend function for a member function, then friend function has one extra parameter because being a non-member of the class, it does not have the caller object. Therefore, it does not have this pointer.
- Friend functions are very useful for overloading certain types of operators. They also make creation of some type of I/O functions easier.
- Consider following example of class 3D having data members x, y and z. Overloaded binary operator * for scalar multiplication. It should work in both cases :
ob1 = ob2 * 3;
ob1 = 3 * ob2;
- Note that first can be achieved through member or friend function. But for the second case we need to write friend function since there is no caller object.
class 3D
{
int x, y, z;
public:
3D (int a=0, int b=0, int c=0)
{
x = a;
y = b;
z = c;
}
3D show()
{
cout<<”The elements are:\n”
cout<<”x:”<<this → x <<”, y:<<this→y <<”, z:”<<this→z;
}
friend 3D operator * (3D, int);
friend 3D operator * (int, 3D);
};
3D operator * (3D ob, int i) //friend function’s definition is written outside class
{
3D tob;
tob.x = ob.x * i;
tob.y = ob.y * i;
tob.z = ob.z * i;
return tob;
}
3D operator * (int i, 3D ob) //friend function’s definition is written outside class
{
3D tob;
tob.x = ob.x * i;
tob.y = ob.y * i;
tob.z = ob.z * i;
return tob;
}
int main()
{
3D pt1(2,-4,5), pt2, pt3;
pt 2 = pt1 * 3;
pt3 = -2 * pt1
cout << “\n Point one’s dimensions are: \n“<< pt1.show();
cout << “\n Point two’s dimensions are: \n“<< pt2.show();
cout << “\n Point three’s dimensions are: \n“<< pt3.show();
return 0;
}
- The output would be :
Point one’s dimensions are:
x:2, y:-4, z:5
Point two’s dimensions are:
x:6, y:-12, z:15
Point three’s dimensions are:
x:-4, y:8, z:-10
- Thus, friend functions are useful when we have to overload operators which have no caller object.