+ 3
Friend ostream operator not for non-class types?
Hello, I was recently experimenting with using the ostream operator as a friend of a class, that didn't have a class object as a parameter, and this gave an error, and when I declare it globally, it works fine. I don't ever recall reading about this. I was wondering if anyone had insight into why this happens. An example code to explain the problem is here: https://code.sololearn.com/cM5H9k1oDM7F
4 Answers
+ 2
Abhay I mean there isn't any overload for this class by default, that's why implementation of this should be as a non-member operator.
But looking at the question again makes me realise that OP is actually asking why is compiler not able to detect definition of "friend ostream& operator<<(ostream& out, any x)" when defined inside the class, and they have to make the definition globally available (unlike the other overload of the same operator )
The answer is because "operator<<(ostream& out, any x)" is defined inside the class and there is no way for compiler to know about the same when looking for it's definition from the call site ( i.e. main() in this case ).
But in case of "operator<<(ostream& out, const Test& t)" the compiler finds the correct location of the definition with the help of its argument ( Test& T ).
Know more about argument dependent lookup here đ
https://en.cppreference.com/w/cpp/language/adl
+ 2
When doing
cout << x;
You are actually calling operator(<<) of "ofstream" class which doesn't have any overload that takes your class's object as parameter, so the only viable option is to implement it as a non-member operator.
+ 2
Arsenic you say that it doesn't have any overload for << operator but then why is this function called ?
friend ostream& operator<<(ostream& out, const Test& t)
{
out << t.x;
return out;
}
+ 1
Arsenic, thank you! That was what I was looking for