Previous section   Next section

Imperfect C++ Practical Solutions for Real-Life Programming
By Matthew Wilson
Table of Contents
Chapter 19.  Casts


19.1. Implicit Conversion

On our behalf, the C++ compiler will carry out a multitude of implicit conversions between types. Just because they're implicit, however, doesn't mean that they're trivial. Conversions between integral and floating-point types can involve significant work [Meye1996, Stro1997]; conversion between integral types of difference sizes can involve truncation or sign extension [Stro1997]; conversions between pointer types of virtually derived classes on an implementing instance involve pointer adjustment [Lipp1996]. The problems, from the point of view of accuracy, of conversions were mentioned in Chapter 13, and are described in detail in [Stro1997]. In this section, we examine what support we get from the compiler to perform these and other conversions, and how we can enhance that support.

The imperfect practitioner's tool kit doesn't contain anything useful for us in such cases, and it is not really the case that there is anything wrong here, excepting the integral truncation and extension issues. It would be a very verbose language indeed that would not allow implicit conversion from int to double, or from 123 to int.

Casts don't always involve converting something. A cast can also be a means of getting access to another nature of an entity, a nature that it already possesses. For an instance of a composite type, say a derived class, the compiler will—issues of access and ambiguity aside—implicitly convert the pointer or reference variable of its type to one of its base class(es).

Indeed, it is possible to access a nature of an entity that does not even directly possess that nature. This is achieved, for class types, by implementing an implicit conversion operator [Meye1996, Meye1998, Sutt2000, Stro1997]. In such cases, a genuine type change is involved, and this is something of which we should be aware when we use the technique. Naturally, the technique has great potential to be abused, and its use is not recommended in most circumstances [Meye1996, Sutt2000, Stro1997, Dewh2003].


      Previous section   Next section