What's the difference between cout<<cout and cout<<&cout in c++?
Asked Answered
T

5

8

This might be a beginner question and understanding how cout works is probably key here. If somebody could link to a good explanation, it would be great. cout<<cout and cout<<&cout print hex values separated by 4 on a linux x86 machine.

Theocritus answered 20/9, 2011 at 17:17 Comment(5)
Here is an example for people. ideone.com/0FZXZHuffy
What actually is the question?Complement
Why are you asking this. The question does not make any sense their is no logic in doing that.Washbowl
@Tux-D: Why I asked it: I saw this idiom somewhere and it confused me. I understood why cout<<&cout would print the address of the current instance but not what it meant when we print cout<<cout Regarding the logic in doing that: Left as an exercise for the reader? :PTheocritus
@DanielA.White: Nothing there.Indubitable
O
16

cout << cout is equivalent to cout << cout.operator void *(). This is the idiom used before C++11 to determine if an iostream is in a failure state, and is implemented in std::ios_base; it usually returns the address of static_cast<std::ios_base *>(&cout).

cout << &cout prints out the address of cout.

Since std::ios_base is a virtual base class of cout, it may not necessarily be contiguous with cout. That is why it prints a different address.

Overplus answered 20/9, 2011 at 17:24 Comment(0)
I
5

cout << cout is using the built-in conversion to void* that exists for boolean test purposes. For some uninteresting reason your implementation uses an address that is 4 bytes into the std::cout object. In C++11 this conversion was removed, and this should not compile.

cout << &cout is printing the address of the std::cout object.

Ideality answered 20/9, 2011 at 17:24 Comment(0)
P
4

cout << &cout is passing cout the address of cout.

cout << cout is printing the value of implicitly casting cout to a void* pointer using its operator void*.

Pileup answered 20/9, 2011 at 17:23 Comment(1)
I removed the link since I could not find a suitable replacement. ThanksPileup
C
3

As already stated, cout << cout uses the void* conversion provided for bool testing (while (some_stream){ ... }, etc.)

It prints the value &cout + 4 because the conversion is done in the base implementation, and casts to its own type, this is from libstdc++:

operator void*() const
{ return this->fail() ? 0 : const_cast<basic_ios*>(this); }
Cyrie answered 20/9, 2011 at 17:33 Comment(0)
H
0

cout<<&cout is passing the address of cout to the stream.

Huffy answered 20/9, 2011 at 17:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.