I’m curious how the fstream class is able to return a true or false value by simply placing the name of the object inside a conditional statement. For example…
std::fstream fileStream;
fileStream.open("somefile.ext");
if (!fileStream) // How does this work?
std::cout << "File could not be opened...\n";
I ask this because I want my own class to return a value if I use it in a similar way.
It’s not really that it is equal to true or false, but rather that it overloads the
!operator to return its status.See http://www.cplusplus.com/reference/iostream/ios/operatornot/ for the details.
Doing this yourself is very simple, check out the operator overloading faq or C++ Operator Overloading Guidelines.
Edit:
It’s been pointed out to me that
iosalso overloads thevoid *conversion operator, returning a null pointer in the case of a failure. So you could also use that approach, also covered in the previously mentioned faq.