Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

stream output and implicit void* cast operator function invocation

Tags:

c++

a code like

cin>> grade;

where grade is a standard data type returns a reference to cin(istream object) which enables cascaded inputs....
but i read that if

cin >>grade;

is used as a condition say in a while statement...the stream's void* cast operator function is called implicitly...and it converts reference to istream object into a non-null or null pointer depending upon success or failure of last input operation...and null pointer converts to false and non-null to true...my questions are:

  1. what is the void * cast operator function and how does it work here
  2. how is non-null pointer converted to true and null to false
like image 572
AvinashK Avatar asked Jun 08 '11 11:06

AvinashK


1 Answers

1.what is the void * cast operator function and how does it work here

It looks something like this:

operator void* () const {
    return fail() ? 0 : this;
}

The question is: why isn’t an operator bool used here? The answer is: because that allows invalid conversions which may hide bugs. The above is an example of the safe bool idiom.

However, this implementation is actually obsolete. There exist better implementations of this idiom; the article explains them.

2.how is non-null pointer converted to true and null to false

This is just how C++ works: any non-null pointer is considered equivalent to true in a conditional. Now, why does C++ invoke the operator void* here in the first place?

Essentially, when C++ sees an object of an unexpected type, it tries to apply one implicit conversion that would make the object type valid in this context. The compiler therefore tries out all available implicit conversions and looks whether the resulting type would be acceptable in this context.

This is happening her: the compiler sees while (cin >> grade). It knows that basic_istream isn’t valid in the context of a while conditional. So it finds that there is an operator void*, and a void* is valid in this context so C++ applies this conversion.

like image 54
Konrad Rudolph Avatar answered Oct 06 '22 20:10

Konrad Rudolph