3

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

Vineel Kumar Reddy
  • 4,330
  • 9
  • 32
  • 36
  • The answer is available here as well : [delete cout; delete cin; do not give compilation error - a flaw in the Standard library?](http://stackoverflow.com/questions/7453583/delete-cout-delete-cin-do-not-give-compilation-error-a-flaw-in-the-standard-l) – Nawaz Sep 25 '11 at 05:59

3 Answers3

3

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.

Frédéric Hamidi
  • 249,845
  • 40
  • 466
  • 467
3

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

struct ifstream {
  typedef void * voidptr;
  operator voidptr() const;
};
Vaughn Cato
  • 61,903
  • 5
  • 80
  • 122
3

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.)

CB Bailey
  • 700,257
  • 99
  • 619
  • 646