Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: how is istream is converted to bool inside a conditional expression [duplicate]

Tags:

c++

istream

The istream operator>> is used to read the data and the function returns reference to istream.

For example,

istream& operator>> (bool& val);

But how does the istream is converted into a bool when it is used inside the conditional statement.

For example,

ifstream ifs(.....);  // open the file
istream &is = (istream&)ifs;

char c;

if(is >> c)   // how the istream is been evaluated into as bool
{
    // character read
}

Can anyone explain how it is being converted into a bool inside a conditional expression?

like image 898
veda Avatar asked Mar 23 '23 19:03

veda


1 Answers

From cppreference:

   explicit std::basic_ios::operator bool() const;

Returns true if the stream has no errors occurred and is ready of I/O operations. Specifically, returns !fail().

So since an if statement is a boolean context, it will invoke std::istream's member function operator.

like image 195
David G Avatar answered Apr 06 '23 19:04

David G