I was trying to write some operator overload functions, especially the <<
operator to use it with a custom class and an std::ofstream
object, but I was a bit confused by the syntax used in various examples found online. For example, let's consider the operator<<
overload as a non-member function for a simple custom class:
#include <fstream>
class Example {
public:
int first;
int second;
};
// I found this kind of operator on the Internet
std::ofstream& operator<< (std::ofstream& out, Example obj) {
out << obj.first << endl << obj.second;
return out;
}
int main() {
Example a={1,2};
std::ofstream out;
out.open("test");
out << a;
out.close();
}
I don't really get why It should return std::ofstream&
to work properly. I tried using the following operator
void operator<< (std::ofstream& out, Example obj) {
out << obj.first << endl << obj.second << endl;
}
and it worked as well. I mean, can't out << obj;
be interpreted as operator<< (out , obj);
? Why does it have to return something since I'm passing a reference to the std::ofstream
object?
The same doubt arose when I was trying to write an operator=
overload as a member function for a custom class, as the simple example that follows
class Custom{
public:
int up;
int down;
Custom& operator= (Custom a) {
up=a.up;
down=a.down;
return *this;
}
};
I used the copy-swap idiom for the assignment operator, so don't mind the operator definition too much, it's just an example. Again, writing
Custom obj1, obj2;
obj1 = obj2;
since I can interpret obj1 = obj2;
as obj1.operator=(obj2)
, why is the return type Custom&
required instead of void
?