3

Possible Duplicate:
What's the difference between cout<<cout and cout<<&cout in c++?

I accidentally found:

cout << cout;

The output is some address. What does this address mean, and why is it shown?
I am looking this question.

Thanks

Community
  • 1
  • 1
Swathi Appari
  • 193
  • 1
  • 1
  • 12

2 Answers2

9

Because ostream overload operator void*(), and that's the closes match for the call to operator <<, the result of the cast (void*)cout is printed. Which in your case is that address. Remember that cout is an object.

Basically the call translates to:

cout.operator<<((void*)cout);
Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
  • why c++ used << operator? calls a function without parenthesis? – Pooya Jul 09 '12 at 08:06
  • 2
    @Pooya in C++ you can overload operators for convenience in typing. Research the subject, too much to explain in a comment. – Luchian Grigore Jul 09 '12 at 08:14
  • yes, I know the operator overloading, but you use << for lift shifting according to right operand – Pooya Jul 09 '12 at 08:22
  • 2
    @Pooya, While in C, it was strictly used for that, in C++, it became overloaded for streams like the input and output streams. It doesn't really have anything to do with bit shifting any more when it's used like that. You can make `operator+` do subtraction, but the difference is that here, they've drilled it in to make sense in the context, whereas my example is absurd. – chris Jul 09 '12 at 08:24
  • 1
    yes, I found that, in c++ ostream and istream has override << and >> as operator for input and output – Pooya Jul 09 '12 at 10:13
2

cout is an ostream object that have an overloaded insertion(<<) operator. If we look at the constructor of the ostream class, there is an argument to be passed which is a pointer to streambuf object. streambuf objects are normally associated with a character sequence which they use to read and write data. For a console application there will be such a character buffer associated with the standard output which might be used internally in case of cout. It is said in the documentation that we are not expected to directly instantiate the ostream object but use any of the derived classes, ofstream or ostringstream diverting attention from stdout.

Regarding the address getting printed, I think Luchian Grigore is right.

This question will get you an idea on how and where the cout object is instantiated: How is the object std::cout constructed/instantiated

Community
  • 1
  • 1
Ragesh Chakkadath
  • 1,521
  • 1
  • 14
  • 32