Let's say you have a class of some type, but you would like to be able to cast it to some other, probably atomic type much like you can cast a float to an int. C++ allows you to do this by creating cast operators. A cast operator gets called whenever you either explicitly or implicitly cast an object to a type that it does not directly inherit.

The syntax for declaring a cast operator is quite precise. It must appear in the form operator castType(); where castType is the type that the operator casts to. The declaration can not indicate the return type, but must return a variable of the type being cast to.

One nice use of cast operators is for wrapper classes. If you are writing a class that wraps some type used in an API, you can write cast operators that cast your wrapper to that type so that you can call functions in the API and pass in your objects directly. For example, I wrote a string class wrapper that had a cast operator for the type Str255 which is what the Mac OS uses in its functions for passing strings. This way, whenever I wanted to call DrawString, I could simply pass in one of my strings and rely on the cast operator to take care of the conversion, making the code much more readable.

The example below shows a class for a complex number with a cast operator to convert to a float. It then shows three ways in which the operator may be invoked.

class Complex
    Complex( float a, float b )
    { m_a = a; m_b = b; }

    // cast operator to convert a complex number
    // to a float (i.e. just return the real portion)
    operator float()
    { return( m_a ); }

    float m_a, m_b;

float HalveFloat( float f )
    return( f / 2.0 );

int main( void )
    float z;
    Complex comp( 2.5, -3.1 );

    // explicit cast
    z = (float)comp;

    // implicit cast
    z = z + comp;

    // implicit cast by parameter type
    z = HalveFloat( comp );

    return( 0 );

Log in or register to write something here or to contact authors.