Search code examples
c++doublestatic-cast

How to use static_cast with a custom object?


I'm trying to use the static_cast that seems simple but I can't figure out what I'm doing wrong. I have the class Rat (used to represent rational numbers) and I want to cast it to a double. Then I could do double x = Rat(2,3) (it would store 2/3 into the x).

To do that I need to do a static_cast so I tried double x = static_cast<double>(Rat(2,3)) but I get the error Cannot convert Rat to double without a conversion operator.

How can I fix my problem ?


Solution

  • You can only use static_cast if the type you cast and the one you cast to are related, or when the compiler knows how to perform that cast.

    Cannot convert Rat to double without a conversion operator

    Tells you that there is no conversion operator for Rat that allows the compiler to cast it to double.

    A conversion operator would look this way:

    struct Rat {
     // …
     operator double() const { 
        // … perform a conversion to double …
     }
     // …
    }
    

    Depending on if you want to allow implicit conversion or not, you need to add explicit in front of operator.

    Without explicit you can write:

    double x = Rat(2,3);
    

    With explicit you need a cast:

    double x = static_cast<double>(Rat(2,3));
    

    Normally explicit is preferred, to avoid accidental casts.