"cppaddict" <cp*******@yahoo.com> wrote in message
news:JY****************@newssvr27.news.prodigy.com
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)
//
--
John Carson
1. To reply to email address, remove donald
2. Don't reply to email address (post here instead)