The second way to produce automatic type
conversion is through operator
overloading.
You can create a member function that takes the current type and converts it to
the desired type using the operator keyword followed by the type you want
to convert to. This form of operator overloading is unique because you
don’t appear to specify a return type – the return type is the
name of the operator you’re overloading. Here’s an
example:
With the constructor technique, the
destination class is performing the conversion, but with operators, the source
class performs the conversion. The value of the constructor technique is that
you can add a new conversion path to an existing system as you’re creating
a new class. However, creating a single-argument constructor always
defines an automatic type conversion (even if it’s got more than one
argument, if the rest of the arguments are defaulted), which may not be what you
want (in which case you can turn it off using explicit). In addition,
there’s no way to use a constructor conversion from a user-defined type to
a built-in type; this is possible only with operator
overloading.