O'Reilly logo

C++ Primer Plus by Stephen Prata

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Conversion Functions

Listing 11.18 converts a number to a Stonewt object. Can you do the reverse? That is, can you convert a Stonewt object to a double value, as in the following?

Stonewt wolfe(285.7);double host = wolfe;  // ?? possible ??

The answer is that you can do this—but not by using constructors. Constructors only provide for converting another type to the class type. To do the reverse, you have to use a special form of a C++ operator function called a conversion function.

Conversion functions are user-defined type casts, and you can use them the way you would use a type cast. For example, if you define a Stonewt-to-double conversion function, you can use the following conversions:

Stonewt wolfe(285.7);double host = double (wolfe);      // ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required