How can std::cin return a bool and itself at the same time?

[…] so that must mean that the operator returns a bool […]

Nope, it returns std::cin (by reference). The reason why while(std::cin >> value); works is because std::istream (which is the type of std::cin) has a conversion operator.

A conversion operator basically permits a class to be implicitly (if it is not marked explicit) to be converted to a given type. In this case, std::istream defines its operator bool to return whether an error (typically failbit) occurred;

[std::ios_base::operator bool()]

Returns true if the stream has no errors and is ready for I/O operations. Specifically, returns !fail().


explicit operator bool() const;

Note than even though the operator is explicit (which shouldn’t allow implicit conversions like if (std::cin);), the qualifier is ignored when used in a context that requires a bool, like if, while loops and for loops. Those are exceptions though, not rules.

Here is an example:

if (std::cin >> value);  //OK, a 'std::istream' can be converted into a 'bool', which 
                         //therefore happens implicitly, without the need to cast it: 

if (static_cast<bool>(std::cin >> value)); //Unnecessary

bool b = std::cin >> value;  //Error!! 'operator bool' is marked explicit (see above), so 
                             //we have to call it explicitly:

bool b = static_cast<bool>(std::cin >> value); //OK, 'operator bool' is called explicitly

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)