129k views
5 votes
In a class, why do you include the function that overloads the stream insertion operator, <<, as a friend function? (5, 6)

User Hayley
by
6.2k points

1 Answer

2 votes

Answer:

To provide << operator access to non-public members of the class.

Step-by-step explanation:

Whenever we overload << operator, an object to ostream class has to be passed as this is the class which has properties which allows printing of output to console. Moreover, this operator is used outside class all the time so if not made a global member it will produce conflicts so thats why it has to be made a friend function to allow efficient access to private members of the class. Its declaration inside class is as follows :

friend ostream& operator<<(std::ostream& os, const T& obj) ;

User Yogurtu
by
5.8k points