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
  • 16,721
  • 7
  • 55
  • 78
Suslik
  • 703
  • 6
  • 24

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
  • 697,062
  • 78
  • 1,055
  • 1,465
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
  • 369,052
  • 73
  • 620
  • 1,021
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,736
  • 1
  • 14
  • 33