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;You can't overload on explicitness, but you can provide an explicit converting constructor and implicit conversion operator:
int iVal = (double)dVal;
#includeThe output of the above program is:
templatestruct st_Ctr_test {
st_Ctr_test() {}
templateexplicit st_Ctr_test(const st_Ctr_test &) { std::cout template operator st_Ctr_test() { return st_Ctr_test(this); }
private:
templatefriend struct st_Ctr_test;
templatest_Ctr_test(const st_Ctr_test *) { std::cout };
int main () {
st_Ctr_testst_SD;
st_Ctr_testsi1(st_SD);
st_Ctr_testsi2 = st_SD;
}
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