[   ^ to index...   |   <-- previous   |   next -->   ]

Casts and conversions

With the three casts defined on the previous page, plus const_cast, C++ now contains enough casts to subsume all the usual uses of C-style casts. Stroustrup recommends that you henceforth abandon all C-style casts, which (among other things) can be used to circumvent encapsulation and the type system in nasty ways.

However, there are a number of other kinds of type conversions that we'd like to define. For example, we would like to be able to convert between user-defined class instances automatically, just as we automatically promote "int" or "short" to "long" on demand.

We can define conversions in a number of ways. One is to overload the conversion operator between two types:

class AsciiText { public: AsciiText(const char* init_contents); AsciiText& operator=(const AsciiText& other); // ... }; class HTMLText { public: operator AsciiText(); // conversion operator // ... }; AsciiText ascii; HTMLText html; // ... ascii = html;

What's going on here? When we attempt to assign the HTMLText instance to AsciiText, C++ attemps to find a "good fit" for the right-hand side of the assignment. However, the method AsciiText::operator= is only defined with an AsciiText argument.

Now, things get interesting: C++ will attempt to "fit" the HTMLText instance to the AsciiText assignment operator. In doing so, it will invoke the user-defined operator AsciiText, resulting in the proper conversion

Q: Why wouldn't we just overload the assignment operator directly, as follows?

class AsciiText { // ... AsciiText& operator=(const HTMLText& html_other); };

Answer: Good question. There's a difficult design decision here: type conversions often overlap in functionality with other user-defined overloaded operators, so it is usually not a good idea to define both kinds. Which you choose will depend on taste and the situation at hand.


Last modified: Thu Jul 27 01:55:13 PDT 2000