difference between reference & pointers in C++
June 13, 2012
Should we use user-defined type conversions
June 13, 2012

User-defined type conversions in C++ (Single argument constructor & implicit type conversion operators function)

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

- Single Argument constructor.
- implicit type conversion operators.

Explain them

Solution:

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

    class Rational
    {
        private:
            int numerator, denomenator;
        public:
            /* 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.

1 Comment

  1. […] I talked about what are user-defined conversions and how Single Argument constructor and overloaded type conversions operators act as type […]

Leave a Reply

Your email address will not be published. Required fields are marked *