Suppose you want to be able to pass a Fraction object to a function that expects a float, that is, you want to convert Fraction objects into floating-point values. The following example defines a conversion operator to do just that:
// Conversion member function
#include <iostream.h>
class Fraction
{
public:
Fraction( long num, long den = 1 );
operator float() const;
// ...
};
Fraction::operator float() const
{
return (float)numerator / (float)denominator;
}
The function operator float converts a Fraction object to a floating-point value. Notice that the operator function has no return type and takes no parameters. A conversion operator must be a nonstatic member function; you cannot define it as a friend function.
You can call the conversion operator using a variety of syntaxes:
Fraction a;
float f;
f = a.operator float(); // Convert using explicit call
f = float( a ); // Convert using constructor syntax
f = (float)a; // Convert using cast syntax
f = a; // Convert implicitly
The compiler can perform a standard conversion and a user-defined conversion at once. For example:
Fraction a( 123, 12 );
int i;
i = a; // Fraction -> float -> integer
The compiler first converts the Fraction object into a floating-point number. Then it performs a standard conversion, making the floating-point number into an integer, and performs the assignment.
A conversion operator doesn't have to convert from a class to a built-in type. You can also use a conversion operator that converts one class into another. For example, suppose you had defined the numeric class FixedPoint to store fixed-point numbers. You could define a conversion operator as follows:
class Fraction
{
public:
operator FixedPoint() const;
};
This operator would permit implicit conversions of a Fraction object into a FixedPoint object.
Conversion operators are useful for defining an implicit conversion from your class to a class whose source code you don't have access to. For example, if you want a conversion from your class to a class that resides within a library, you cannot define a single-argument constructor for that class. Instead, you must use a conversion operator.