0

Why when you write std::cout twice it shows the hexadecimal value and then what you wanted to output?

E.g.

std::cout << std::cout << "Hello!";
Porky
  • 13
  • 1
  • 2
  • 4

2 Answers2

2

std::cout has a type std::ostream (or something derived from it). There is no << which takes this type on the right, so the compiler looks for a conversion. In pre-C++11, std::ostream converts implicitly to void* (for use in conditionals), so the compiler uses this; what you're seeing is the output of what the conversion operator returns (typically, the address of the std::ostream object itself, but all that is required is that it be a non-null pointer).

James Kanze
  • 150,581
  • 18
  • 184
  • 329
0

std::ostream has a conversion operator that allows conversion to void* so you can test if operation was successful. In expression

std::cout << std::cout  // similar to 
                        // std::cout.operator<<( std::cout.operator  void*())

the right-hand operand expression std::cout is implicitly converted to void const* using this conversion operator and then the operator<< does the output of this via the ostream operand . Another way to see this is:

const void* cp = std::cout.operator  void*();
std::cout << cp << "Hello!" << std::endl;
std::cout << std::cout << "Hello!";

output:

0x601088Hello!

0x601088Hello!

4pie0
  • 29,204
  • 9
  • 82
  • 118