what is the purpose of defining explicit constructor in a class? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

what is the purpose of defining explicit constructor in a class?

18th Aug 2016, 7:14 PM
Amit Gupta
Amit Gupta - avatar
7 Answers
+ 1
Example at http://www.sololearn.com/app/cplusplus/playground/cpJm5c30n78T/. Make the constructor of class A explicit and one of the implicit conversions doesn't happen.
18th Aug 2016, 10:29 PM
Stefan
Stefan - avatar
0
The C++ compiler does a lot of things to ease our lives as programmers, e.g. writes the default constructors, the copy constructors, the assignment operators and many conversions between types, if they are not manually written. One parameter constructors can be seen as a converter of the type of parameter to the type of the instance constructed. The C++ compiler automatically uses constructors to provide these conversions. Unfortunately, these automatic conversions are a considerable number of times cause for errors. Making a constructor explicit prevents the compiler from implicitly using it for type conversion. To use such a constructor you need to explicitly call it.
18th Aug 2016, 8:46 PM
Stefan
Stefan - avatar
0
thanks, agree with you, that's what I knew. do you have something in mind to show the proper difference of using and not using explicit constructor?
18th Aug 2016, 9:15 PM
Amit Gupta
Amit Gupta - avatar
0
thanks
18th Aug 2016, 10:48 PM
Amit Gupta
Amit Gupta - avatar
0
My pleasure, Amit :-)
18th Aug 2016, 10:51 PM
Stefan
Stefan - avatar
0
what is the difference between implicit and explicit ??
17th Sep 2016, 3:33 PM
deepika
0
Implicit means some aspect of a statement is not separately stated but included in what is being said. Explicit is the opposite of implicit, i.e. you separately state some an aspect of a statement.
17th Sep 2016, 4:15 PM
Stefan
Stefan - avatar