Page 1 of 1

Why we can use "while(cin >> a)"

Posted: Tue Dec 26, 2006 1:37 pm
by Yile
I read some manual and find that the operator >> returns *this, the type should be istream&. Then why can we put it in the while statement as a condition?

Posted: Tue Dec 26, 2006 2:43 pm
by Krzysztof Duleba
Streams have bool operator() (conversion operator to bool) that returns !this->failed().

Posted: Tue Dec 26, 2006 4:35 pm
by Yile
Where is the operator defined? The class hierarchy is as follows:

Code: Select all

basic_istream->basic_ios->ios_base
Which class is it defined in? I'm afraid I can't find it.

Posted: Tue Dec 26, 2006 4:53 pm
by Krzysztof Duleba
Oh, actually for some reason it's operator void* and not operator bool that's used here. It's a member of basic_ios.

Posted: Wed Dec 27, 2006 7:29 am
by ImLazy
Yes, I find it in the basic_ios.h.

Code: Select all

/**
 *  @brief  The quick-and-easy status check.
 *
 *  This allows you to write constructs such as
 *  "if (!a_stream) ..." and "while (a_stream) ..."
*/
operator void*() const
{ return this->fail() ? 0 : const_cast<basic_ios*>(this); }

Posted: Wed Dec 27, 2006 2:34 pm
by Krzysztof Duleba
Just to make clear, if (!a_stream) is using bool operator!, not operator void*.

Posted: Thu Jun 21, 2007 1:43 pm
by saman_saadi
Krzysztof Duleba right there is a converstion operator. for example:

Code: Select all

#include <iostream>

using namespace std;

struct test
{
	int a;
};

int main()
{
	test a;
	while (a)	// Syntax error
	{
	}

	return 0;
}
but if you define a conversion operator the code will be correct:

Code: Select all

#include <iostream>

using namespace std;

struct test
{
	int a;
	operator bool()
	{
		return true;
	}
};

int main()
{
	test a;
	while (a)	// No syntax error
	{
	}

	return 0;
}
so you can use:
while (cin)
or
while (cin >> n)

for finding this operator see the source code of your compiler (I don't remember which header file). for example in MSDN there is a void * operator and there is no bool operator but if you see the source codes you will find a bool operator