You can do this, but only when you're using the copy-initialization syntax to call your constructor. For example:
main()
{
if (A a = A())
{
// do stuff
}
}
Most compilers would elide the copy constructor in such an initializer when optimizations are enabled, but an accessible constructor is required nonetheless.
Also, naturally, if A
would have a constructor such as A(int)
, you could also do this:
if (A a = 123) ...
Also, it is generally considered a bad idea to have operator bool()
on your class for such purposes. The reason is that bool
is in turn implicitly convertible to any numeric type (with false == 0 && true == 1
); so, for example, the client of your class can write:
int x = A();
void foo(float y);
foo(A());
which is probably not something you want to allow. A simple trick is to use a pointer-to-member-of-private-class instead:
class A {
private:
struct dummy_t { int dummy; };
typedef int dummy_t::*unspecified_boolean_type;
public:
operator unspecified_boolean_type() const {
if (...) {
return &dummy_t::dummy; // true
} else {
return 0; // false
}
}
};
Pointers-to-members have an implicit bool
conversion (as usual, null pointer is false
, anything else is true), but they are not compatible with any type but their own; and, since the inner class here is private, no client code can possibly declare a variable of that type (auto
and decltype
in C++0x provide a way, though).
As a side note, main()
as written is not valid C++ - ISO C++ does not have "default int
" rule the way C does, and a function without an explicit return type is invalid.