user3139831
user3139831

Reputation:

When should I return std::ostream?

I return std::ostream every time I'm going to create an operator like std::string operator to show value (no operator), but I don't know why. If the std::ofstream is used as an function member operator function(std::cout), how can I return it, when should I do it and why?

Example:

class MyClass
{
   int val;
   std::ostream& operator<<(const std::ostream& os, const MyClass variable)
  {
      os << variable.val;
  }
}

On std::string:

std::string a("This is an example.");
std::cout << a;

Upvotes: 1

Views: 1046

Answers (1)

Mike Seymour
Mike Seymour

Reputation: 254501

It's conventional to return a reference to the ostream when overloading <<, to allow chaining. This:

s << a << b;

is equivalent to the function calls

operator<<(operator<<(s,a),b);

and only works because the inner call returns a suitable type to be an argument to the outer call.

To implement this, simply take the stream argument by reference, and return the same stream by reference, either directly:

std::ostream & operator<<(std::ostream & s, thing const & t) {
    // stream something from `t` into `s`
    return s;
}

or as returned from some other overload:

std::ostream & operator<<(std::ostream & s, thing const & t) {
    return s << t.whatever();
}

Upvotes: 6

Related Questions