please respond :)

I really cant understand how I/O operator overloading works behind the scenes
please some1 explain in detail what is really going on, why use return by reference?

1
2
3
4
5
6
  friend std::ostream &operator << (std::ostream &output, const ClassName &object)
   {
       output<< object.member1 <<", "<<object.member2<<'\n';
       return output;
   }

thanks in advance
Last edited on
The code does not compile and is illegal.

'Cause you can't declare a variable name, a parameter name, a member name etc that matches a keyword defined in the language.

friend std:: ostream &operator << (std:: ostream &output, const ClassName &class)
that was just an example . i need answer how this function works and why return by reference
I've always wondered what illegal meant. I hear it a lot on the forums.
closed account (E0p9LyTq)
Why the reference in the parameter list? Because you don't want to copy the output stream you are adding your output into.

Same with the class object parameter, copying can be an expensive operation.
closed account (E0p9LyTq)
I've always wondered what illegal meant.

illegal code = code that won't compile, code that is not part of the C/C++ standard.
> why use return by reference
for chaining.
output << "foo " << obj << " bar\n";
when you apply the insert operation to an strem, you modify said stream. So << "foo " would modify `output' and then you need to work with that modified object to send `obj'.


> Because you don't want to copy the output stream
also, you can't copy it.
Last edited on
how could i have been so stupid :)) ofc its for chaining :)) thanks alot
Topic archived. No new replies allowed.