Vineel Kumar Reddy
Vineel Kumar Reddy

Reputation: 4726

which operator overloading has been used for ifstream object to evalute to boolean

I am new to C++. recently I come across the following code

ifstream in("somefile");

if(in){
    //read the file....
}

I am wondering which operator overloading the ifstream might have used for the in object to automatically evaluate to boolean in if condition. I tried but couldnt find a clue. please help me. thank in advance

Upvotes: 3

Views: 337

Answers (3)

CB Bailey
CB Bailey

Reputation: 792517

std::ifstream gets its conversion to bool from it's base class std::ios (std::basic_ios<char>) which has conversion function declared:

explicit operator bool() const;

It returns !fail().

(In the previous version of the standard ISO/IEC 14882:2003, std::basic_ios had a conversion function operator void*() const but this version of the standard has now been withdrawn.)

Upvotes: 3

Vaughn Cato
Vaughn Cato

Reputation: 64308

The void pointer conversion operator is often used for this purpose. Something similar to

struct ifstream {
  typedef void * voidptr;
  operator voidptr() const;
};

Upvotes: 3

Fr&#233;d&#233;ric Hamidi
Fr&#233;d&#233;ric Hamidi

Reputation: 263047

It's actually operator void *.

It's overridden to return a non-zero pointer if the stream is valid, and a NULL pointer otherwise. The pointer it returns is meaningless and should not be dereferenced, it's only there to be evaluated in a boolean context.

Upvotes: 3

Related Questions