Conversion operators in C++

Many a times you will need to use C code along with C++. In such cases, you want to convert your objects to C data types. The typical example is converting C++ string to C character array. How is this conversion achieved?
For such conversion, you have to write conversion operators which are like user defined type casting operators.

Consider a class Integer which has an int data member num.

Integer obj(3);
int m=5;

Now if you have to assign obj to m, you have to convert obj to int first. Let us write the conversion operator for that.

class Integer
{
   int num;
public:
   Integer(int m):num(m){}
   operator const  int ();//conversion operator
   
};
Integer::operator int()
{
   return num;
}


  • Note that the conversion operator does not have a return type - not even void. The return type is deduced from the operator type. 
  • Conversion operators do not take any parameters. 


If you have to convert the Integer object to a float, what will you do? Yes, you will write an operator float()  which would be
Integer::operator float()
{
     return (float)num;
}
Can we use conversion operators to convert from one user defined type to another? Of course yes!!
class Float
{
  float a;
public:
     operator Integer();//Converts Float object to
};

Float::operator Integer()
{
       return Integer((int)a);
}
   
We are converting Float object to Integer object using the conversion operator.

Implicit  and explicit conversion

When you want to convert basic data type like int to an object, you need not write any extra function at all. The conversion takes place using the constructor with single parameter of the type if one is present.

int n1=55;
obj = n1;

The line obj = n1 will not produce any error. Instead it calls the constructor. In some cases, you do not want such implicit conversions. To stop implicit conversion, you can define your constructors as explicit


class Integer
{
   int num;
public:
   explicit Integer&(int m):num(m){}
   ....
   ....
}

Now the line obj=n1 will give a syntax error, as our compiler does not know how to convert Integer object to int. If you want such conversion, write an overloaded assignment operator with int as a parameter

Integer& Integer::operator =(int m)
{
   num = m;
   return *this;

    

You can download the complete program from here

Comments

Popular Posts