c++ - Why can an ifstream object be compared to 0? -
i'm trying learning c++ after having first learned basics 20 years ago setting aside. started picking book had learned from, then. here's 1 of examples (i've figured out has obsolete syntax):
#include <fstream.h> void main() { ifstream infile("iocopy.cpp"); if (!infile) cerr << "couldn't open iopcopy.cpp" << endl; ... other junk } his explanation of ! operator on infile "checks see if object nonzero", confusing me (what mean object zero?). decided try myself:
#include <fstream> #include <iostream> void main () { std::ifstream f ("something"); // if (f == 0) std::cout << "couldn't open file" << std::endl; if (!f) std::cout << "couldn't open file" << std::endl; } this works expected, displaying message if file doesn't exist , nothing if does. works if uncomment line (f == 0) , comment out following line.
i think figured out ! operator here; found operator! in 1 of header files defined return fail field. i'm confused why first example (f == 0) works, though, since didn't see operator== seem apply.
so what's going on? can variable of class type compared 0? there special ifstream variables of type pointers (that compared null or 0)? or there operator== redefinition missed somewhere? i'm more used languages java it's impossible constructor return null value, i'm confused.
c++03
basic_ios (a base class of ifstream) has operator void* makes implicitly convertible void*.
0 valid value void* literal, comparing values of type void*.
c++11
basic_ios (a base class of ifstream) has explicit operator bool makes convertible bool explicit cast. example should not compile.
bool implicitly convertible int per c++ language type conversion rules, if operator bool had not been explicit, comparing values of type int.
Comments
Post a Comment