20-CS-122-001 Computer Science II Spring 2012
User Defined Type Conversion

Virtual functions, classes, inheritance, lists, queues, stacks, applications

Prev      Lectures

Important - otherwise separate functions for all possible type pairs are needed

   Example pair:

       Fraction Fraction::operator*(Fraction &, int);

   We may want to define our own conversions e.g. for comparisons

   Example (Object to type):

       class Fraction {
         ...
         operator double() {    // covert Fraction to double
            return double(num)/double(denom);
         }
         ...
       }

       Fraction frac(3,4);

       cout << double(frac);

       cout << (double)frac;

       if (x > pi && x < double(frac));

       if (x > pi && x < frac)  // works due to implicit type conversion

   Example (type to Object):

       class Fraction {
          ...
          Fraction::Fraction(int j) : num(j), denom(1) {}  // int => Fraction
          ...
       }

       ...

       int i=7;

       frac = frac * Fraction(i);