C++ › Casting & Conversions

What is a user-defined conversion operator?

Advanced

Answer

A conversion operator (operator T() const) lets a class object be converted to another type T implicitly or explicitly. It enables classes to integrate with code expecting T, but implicit conversion operators can cause surprising conversions and ambiguity, so they're often marked explicit (e.g., explicit operator bool() for use in conditions only).
struct Handle {
    explicit operator bool() const { return valid; }
    bool valid = false;
};
if (h) { /* uses explicit operator bool */ }
Real-world example A smart-handle type provides explicit operator bool so it works in if-conditions but not in arithmetic.

Common follow-ups: Why mark conversion operators explicit? | What is the safe-bool idiom?