Information Technology Reference
In-Depth Information
stitute for the target type. Side effects that modify the state of the target
type won't have the same effect on your type. Worse, if your conversion
operator returns a temporary object, the side effects will modify the tem-
porary object and be lost forever to the garbage collector. Finally, the rules
for invoking conversion operators are based on the compile-time type of
an object, not the runtime type of an object. Users of your type might need
to perform multiple casts to invoke the conversion operators, a practice
that leads to unmaintainable code.
If you want to convert another type into your type, use a constructor. This
more clearly reflects the action of creating a new object. Conversion oper-
ators can introduce hard-to-find problems in your code. Suppose that you
inherit the code for a library shown in Figure 1.1. Both the Circle class and
the Ellipse class are derived from the Shape class. You decide to leave that
hierarchy in place because you believe that, although the Circle and Ellipse
are related, you don't want to have nonabstract leaf classes in your hierarchy,
and several implementation problems occur when you try to derive the
Circle class from the Ellipse class. However, you realize that every circle
could be an ellipse. In addition, some ellipses could be substituted for circles.
That leads you to add two conversion operators. Every Circle is an Ellipse,
so you add an implicit conversion to create a new Ellipse from a Circle. An
implicit conversion operator will be called whenever one type needs to be
converted to another type. By contrast, an explicit conversion will be called
only when the programmer puts a cast operator in the source code.
Shape
Circle
Ellipse
Square
Figure 1.1 Basic shape hierarchy.
 
Search WWH ::




Custom Search