0

Explicit Constructor | Why needed

Hi Please refer code below : My class has one int member and it has a method to display int. Constructor is not explicit so mymethod which needs object as argument can be constructed using int argument from main This code works fine. What is need to have this conversion stopped from int to test ? I mean why (for which scenarioes) this explicit constructor is life saver (i.e. if not done as explicit, it will result in failure)? https://code.sololearn.com/cccuOLJmDykQ/?ref=app

29th Nov 2022, 2:44 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
4 Answers
+ 1
I’m not 100% sure what you are asking but here’s a go… You are calling a function, which is expecting a reference to an object of class test. Instead you are passing an integer, so there is an implicit conversion happening - int to test. As the parameter passed matches your constructor, a test object is instantiated using that. However you are not telling it how to instantiate, it’s implied. Adding the specifier explicit to your constructor means it cannot be used for implicit conversions (that’s why it fails) when using explicit. If for example you call your function with an explicit call to the constructor it would work with explicit. Eg. myMethod(test(4));
15th Jan 2023, 12:28 AM
DavX
DavX - avatar
+ 1
No problem. The use of explicit is purely to prevent type casting. To stop conversion. Lets take your code for example, if you were to pass a float… myMethod(4.5f); Your constructor is expecting an integer, this is implicitly converted and works. However in a larger program you might want to avoid this conversion which could produce unexpected results. Adding explicit specifier stops this ability, it will only perform conversions IF they are explicit ( eg you typecast). myMethod(test(4.5f)); // would work with explicit. myMethod(4.5f); // won’ work with explicit, an implied type conversion would take place. This only works with constructors with a single parameter, which are known as conversion constructors. Hopefully this makes a little more sense, its basically to avoid the constructor from applying conversions to the type required without them being explicit.
15th Jan 2023, 11:21 AM
DavX
DavX - avatar
0
Thanks DavX for responding. My question is a different one. Without explicit it works and no issues is observed. Why explicit needed at all ? In which case, constructor not marked as explicit will compile but fail at run time? Basically , what problem explicit keyword is solving ?
15th Jan 2023, 4:05 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
0
Yeah i got this but its side effect not able to visualize Whats a big deal if implicit cast done ? Looking for some real usecase where not using explicit is nightmare. By the way, thanks for sharing this details DavX
16th Jan 2023, 4:11 AM
Ketan Lalcheta
Ketan Lalcheta - avatar