1

I have some problems in understanding the << operator.

If I have:

#include <iostream>
using namespace std;
//...

int t = 5;
cout << "test is: " << t << endl;

Now the function operator<< is called.

ostream& operator<<(ostream& out, string* s)
{
    return out << s << endl;
}


ostream& operator<<(ostream& out, int* value)
{
    return out << value << endl;
}

the string-pointer points to the address with value test is: but to what does the element out refer (to cout?)? and is the function body of ostream& correct in that way?

Thank you so much for any explanation.

Carlos Muñoz
  • 17,397
  • 7
  • 55
  • 80
Suslik
  • 929
  • 8
  • 28

3 Answers3

1

First, let's fix your code: the operators should be taking const references or values instead of pointers:

ostream& operator<<(ostream& out, const string& s) // const reference
ostream& operator<<(ostream& out, int i)           // value

Now to your question: you are correct, the out parameter receives the reference to the cout, or whatever is the ostream& returned from the expression on the left side of <<. The expression on the left of << is not necessarily cout, though - other common cases are results of other << operators* for chaining, and stream manipulators. In all cases these expressions return a reference to ostream so that the "chain" could continue.

* The reason the operator<< return an ostream& is so that you could chain the output. In overwhelming number of cases you wold return the same ostream& that you receive as the first parameter, although there is no limitation on the part of the standard C++ library requiring you to do that.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

This is not true. It's int not int*, and char const* not string*.

out, of course, refers to std::cout in this example. What else would it be?

And no those bodies are not correct in the slightest — they attempt to reinvoke themselves infinitely, and do nothing else.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
  • You mean [`char const*`](http://en.cppreference.com/w/cpp/io/basic_ostream/operator_ltlt2) as the parameter? – Columbo Dec 31 '14 at 17:12
  • @Columbo: Suppose so, yeah (27.7.3.6.4) – Lightness Races in Orbit Dec 31 '14 at 17:20
  • i cant see why they reinvoke themselves infinitely. Because if you overload the operator, you write: return out << v.a <<"/" << v.b; and there is no self invocation. The function body is not necessary, but it should work as an explanation for myself. (parallel to operator-overloading to understand the functionality better) – Suslik Dec 31 '14 at 17:28
0
int t = 5;
cout << "test is: " << t << endl;

First call would be to:-

ostream& operator<<(ostream& out, const char* str)

out = cout

str = "test is: "

Second call would be applied on object returned by first call which is ostream.

ostream& operator<<(ostream& out, int x)

out = cout

x = t

ravi
  • 10,994
  • 1
  • 18
  • 36