Sunday, 24 July 2016

Diff in Conversion ctr and explicit ctr

Diff in Conversion ctr and explicit ctr, explain with examples:

Before going to know about the difference between the implicit and explicit convertions we need to have a little bit knowledge on casting


Casting means converting form one data type to another. We have two types of castings
·        Implicit casting
·        Explicit casting

Implicit casting

The Implicit casting doesn't require any casting operator. This casting is normally used when converting data from smaller integral types to larger or derived types to the base type.

int iVal = 100;
double dVal = iVal;

Explicit casting: 
Coming to Explicit casting to convert from base type to derived type we can go for Explicit casting. See the below simple example
Double dVal = 29.00;
int iVal = (double)dVal; 
You can't overload on explicitness, but you can provide an explicit converting constructor and implicit conversion operator:
template struct st_Ctr_test {
   st_Ctr_test() {}
   template explicit st_Ctr_test(const st_Ctr_test &) { std::cout << "explicit\n"; }
   template operator st_Ctr_test() { return st_Ctr_test(this); }
   template friend struct st_Ctr_test;
   template st_Ctr_test(const st_Ctr_test *) { std::cout << "implicit\n"; }

int main () {
   st_Ctr_test st_SD;
   st_Ctr_test si1(st_SD);
   st_Ctr_test si2 = st_SD;
The output of the above program is:

The explicit converting constructor is preferred to the implicit conversion operator because in the latter case there is an additional call to the copy constructor.
Problems with the implicit conversion:
By default when you create a user-defined conversion, the compiler can use it to perform implicit conversions. This may lead to get some unexpected results which you do not want really.
A simple daily routine problem safe bool, to avoid this problem we can use explicit keword.
 The explicit keyword tells the compiler that the specified conversion can't be used to perform implicit conversions.  

No comments: