cin question

C

cppaddict

Hi,

When

cin >> myVar

is successful, the ">>" operator returns the cin object. But when it fails
it returns 0, or false. My question is: Since a function can only return
one type, how is this possible? Is the cin object being cast to a boolean?
If so, how does one define, in general, casting for custom classes? If not,
what is going on here?

Thanks,
cpp
 
J

John Carson

cppaddict said:
Hi,

When

cin >> myVar

is successful, the ">>" operator returns the cin object. But when it
fails it returns 0, or false. My question is: Since a function can
only return one type, how is this possible? Is the cin object being
cast to a boolean? If so, how does one define, in general, casting
for custom classes? If not, what is going on here?

Thanks,
cpp

cin always returns a reference to itself, regardless of whether an operation
succeeds or fails. The istream class also contains a "conversion operator",
something along the lines of

operator bool()
{
return everythingOK;
}

where everythingOK is a boolean recording success or failure (the syntax for
this operator is unusual, but it is described in any decent textbook). Thus
if you use

if (cin >> x)
//

then this becomes

if (cin)
//

and, because if () takes a boolean argument, the conversion operator is
called, so it becomes

if (everythingOK)
//
 
M

Micah Cowan

cppaddict said:
Hi,

When

cin >> myVar

is successful, the ">>" operator returns the cin object. But when it fails
it returns 0, or false. My question is: Since a function can only return
one type, how is this possible? Is the cin object being cast to a boolean?
If so, how does one define, in general, casting for custom classes? If not,
what is going on here?

False premise, false conclusion. The >> operator *always* returns
the stream object (cin, in your case), never a bool or an
integer. However, the stream object itself can be converted to
pointer-to-void (or thereby to bool), which will depend on
the return value of the fail() member function.
 
J

John Carson

John Carson said:
cin always returns a reference to itself, regardless of whether an
operation succeeds or fails.

More precisely, the istream >> operator returns a reference to cin when
called from a cin object.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,145
Messages
2,570,825
Members
47,371
Latest member
Brkaa

Latest Threads

Top