How if ('fstream object') returns true or false depending on whether the file was opened?

I am curious how it fstream classcan return a value trueor falseby simply placing the name of an object inside a conditional statement. For instance...

std::fstream fileStream;
fileStream.open("somefile.ext");

if (!fileStream)  // How does this work?
  std::cout << "File could not be opened...\n";

I am asking about this because I want my own class to return a value if I use it in the same way.

+5
source share
2 answers

This does not mean that it is true or false, but rather overloads the operator !to return its status.

See http://www.cplusplus.com/reference/iostream/ios/operatornot/ for more details .

, faq ++ .

: , ios void *, . , , faq.

+5

. , , , , bool, , bool, :

class X
{
public:
  void some_function(); // this is some member function you have anyway
  operator void(X::*)() const
  {
    if (condition)
      return &X::some_function; // "true"
    else
      return 0; // "false"
  }
};

++ 11 bool , , . , ++ 11 :

class X
{
public:
  explicit operator bool() const
  {
    return condition;
  }
};
+3

All Articles