Why We Need To Use Friend Functions When Overloading Insertion And Extraction Operators?


1 Answers

Anonymous Profile
Anonymous answered
In overloading stream insertion operator and stream extraction operator you should know about the left hand side object, for example we write cout<<”hello world”; now look at the left hand side object in this statement which is cout and this object is not the object of the class that you are developing , cout is an object of the ostream class. Now we can make a function a member function of a class in the situation where the left hand side object of the operator belongs to the same class that we are developing.
Suppose I have a date class  and I am overloading + operator for the data class
So that I can add two dates,
For example d3=d1+d2; where d1,d2,d3 are the objects of the date class now look at the + operator the left hand side operand of + operator is d1 which is the object of date class now it means that we can overload + operator as a member function of the class,
Look at another example d3=5+d2; now the left hand side operand is 5 which not the object of the class date, so we can not make this function as member function
We have to make it friend function

Answer Question