The modern versions of C++ attempt to use the bool
operator of a class when evaluating the condition in an if()
statement. Other casting operators, such as int
being use when no bool
operator exists. This is demonstrated below.
#include <iostream>
using namespace std;
class TwoInts {
public:
int a,b;
operator bool() { cout << "TwoInts to bool" << endl; return 0;}
operator int() { cout << "TwoInts to int" << endl; return 0;}
};
class SixInts {
public:
int a[6];
operator int() { cout << "SixInts to int" << endl; return 0;}
};
int main(void) {
TwoInts T;
SixInts S;
if (T) cout << "xxx" << endl;
if (S) cout << "xxx" << endl;
return 0;
}
Running this code produces no surprises:
TwoInts to bool
SixInts to int
Looking over some old C++ code, there appears to be a change that I would like to verify.
Did older versions of C++ use the int
operator of a class when evaluating the condition in an if()
statement? What versions, if any, did that?
The suggested output then would have been
TwoInts to int
SixInts to int
Some details as to why the question: Issues with converting an old big integer class may be due int
vs. bool
in an if()
. No longer have access to the old compiler, so can not test the old behavior.
[Edit]
Using the answers below and some more research:
Answer: Yes, many pre ISO Standard C++ versions (mid 1980s -1998), that lacked a bool
, did use casts to int
(or other numeric types). Significant compiler variation existed - it was pre-standard.
The first C++ ISO standard came out in 1998 (ISO/IEC 14882:1998 aka C++98). It defined the bool
type. Thus ISO standard C++ has always used the bool
cast in if()
.
bool
type altogether. – user657267