Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

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


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:
#include 
template struct st_Ctr_test {
st_Ctr_test() {}
template explicit st_Ctr_test(const st_Ctr_test &) { std::cout template operator st_Ctr_test() { return st_Ctr_test(this); }
private:
template friend struct st_Ctr_test;
template st_Ctr_test(const st_Ctr_test *) { std::cout };

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:
Explicit
implicit

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.  


This post first appeared on Tutorials For C,C++ Programming,course Material For beginners, please read the originial post: here

Share the post

Diff in Conversion ctr and explicit ctr

×

Subscribe to Tutorials For C,c++ Programming,course Material For beginners

Get updates delivered right to your inbox!

Thank you for your subscription

×