Jun 132012

There are 2 types of user-defined conversion functions in C++

- Single Argument constructor.
- implicit type conversion operators.

Explain them


Lets us take the below class as a reference to understand about them

    class Rational
            int numerator, denomenator;

            /* This constructor will act as all
             * default constructor, Single argument constructor
             * and 2-argument constructor, because of default arguments.
            Rational(int num=0, den=1):numerator(num), denomenator(den){}    

Single Argument Constructor:

The single argument type constructor will be used to construct objects when we need to convert int to Rational like below:

    void myfun(Rational r);
    ... ...
    myfun(2);	   // OK;

Because there exist a constructor which take one integer and hence can be used as a convertor to convert int to Rational. Same situation will be in the initializations like below:

    Rational obj = 2;

Implicit Type Conversion:

The C-like type conversion operator of C++ can be overloaded which can convert object of Class to a particular type. For example: the Rational object also has a real number corresponding to it, so the operator function which can convert it to double will look like below (the definition to go inside class)

    operator double() const;

Note, that there is no return type, because return type will be same as the type for which we are overloading (double in this case). This function will be called implicitly when ever compiler detects that a conversion from Rational to double is required. For example:

    Rational obj(1,2); // value of obj will be 1/2
    double x = 3 * obj;

In the second statement obj will be converted to double, the return value will be multiplied with 3 and the value will be stored in x.

This facility is provided by C++ standard but whether or not should we use them is something I will talk about later.

  One Response to “User-defined type conversions in C++ (Single argument constructor & implicit type conversion operators function)”

 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>