How friend works in a struct (for ostream operator <<)? c++ | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

How friend works in a struct (for ostream operator <<)? c++

I was trying to understand how overload << works, but I'm not sure how this works inside Entry struct: friend std::ostream& operator << (std::ostream& os, const Entry& e) { os << "{\"" << e.name << "\"," << e.number << "}"; return os; } cppreference says: "The friend declaration appears in a class body and grants a function or another class access to private and protected members of the class where the friend declaration appears. " So... why do I need "friend" to make the operator << works inside the struct when Entry's members are public? I tried multiple attempts: The attempt 1 it was like that because there is another << operator overloaded (for Dog struct). The attempt 2 is there because the compilers tells me there is an error (because attempt 1). Attempt 3 is there because I thought "maybe I don't need const Entry& because is implicit in the struct, but it didn't work; finally attempt 4 works. Why do I need friend inside the struct for << overloading? Here is the code where I show the multiple attempts: https://code.sololearn.com/ca4a14a9A6A2

19th Feb 2021, 3:21 AM
Eduardo Perez Regin
Eduardo Perez Regin - avatar
2 Answers
+ 2
Saying we have a class named A and it has a working overloaded operator << that takes an ostream& to use. A& operator(ostream& rhs); The correct way to use it will be: A() << std::cout. Hold on, that looks so weird. But, yes, it will work. Because the operator belongs to A, the left operand MUST BE A. So we definitely need friend. Because that means the function does not belong to any class. It just a function that is able to access everything in the class (private, protected, public members). We're not overloading A's <<, we're overloading ostream's <<
19th Feb 2021, 3:46 AM
你知道規則,我也是
你知道規則,我也是 - avatar
+ 1
CarrieForle that makes sense, it wasn't very clear for me about why I needed to use friend, but now is clear for me. Thank you so much!
19th Feb 2021, 4:28 AM
Eduardo Perez Regin
Eduardo Perez Regin - avatar