In: Computer Science
What is a friend function? Do we have to use friend functions? Explain why or why not.
c++
Friend function:
A friend function is not the member function of the class, so there is no 'this' pointer. When we are overloading a unary operator then we have to pass one parameter. This function can access the private member of a class.
The complete program source code using friend function and without friend function is given below:
#include <iostream>
using namespace std;
class Number
{
//private data member
int a;
public:
//default constructor
Number()
{
a = 0;
}
//parameterized consturctor
Number(int num)
{
a = num;
}
//Operator ++ overloading function
Number & operator--(int)
{
a--;
return *this;
}
//display the object values
void display()
{
cout<<endl<<"a = "<<a;
}
//method declaration to overload operator - using frined
function
friend Number operator-(const Number & obj);
};
//method to overload operator - using frined function
Number operator-(const Number & obj)
{
return Number(-(obj.a));
}
int main()
{
//create objects
Number num1(100);
Number num2(200);
num1--;
num2 = -num2;
//display the object on the computer screen
num1.display();
num2.display();
return 0;
}
OUTPUT:
We can use the friend function if it is required to share the data between the two classes. A friend function can be the friend of any number of classes. This function works as a normal function and there is no need for the class object for calling the friend function.
This function is not good from the security point of view because this function can access the private data of more than one class but it is not the member function of any class. Forward declaration of a class is needed if the function is a friend function of two or more classes.