When developing a public API, is it useful to make the constructor explicit?
class A { public: //explicit A(int i){} A(int i){} }; void fun(const A& a) {} int main() { // If I use explicit for A constructor, I can prevent this mistake. // (Or shall I call it as feature?) fun(10); }
Or can I enable implicit conversion to allow the user to call my API with less input?
The constructor should be explicit if the implicit conversion makes sense semantically (for example, what does converting int to A mean?). Less typing should not be the criterion for guiding this decision. Think about readability (which is the main argument for implicit casting) and how well your code should understand. An implicit cast that is not intuitive will cause code readers to scratch their heads.
int
A
PS: I can’t come up with a good example now, so any help is appreciated.
Yes, by default, any constructor that can be called with one argument must be explicit. By following this rule, you will avoid subtle mistakes that are extremely difficult to find.
Of course, there are exceptions to this rule:
Implicit conversion may be desirable if your class has wrapper semantics around one parameter.
Copy constructors need not be explicit (otherwise you will lose the ability to callbacks).
This is what I found in response from "Daniel Krügler"
If we started creating C ++ from today, there is a good chance that all the constructors and conversion functions were “explicit” by default, but the user can do “Implicit”. Alas, time cannot be back, and we must live with the current state. This means that we must be careful about implicit constructors (with the exception of copy / move constructor). It is a safer rule to make constructors explicit, where some form of conversion (i.e. any constructor with argument type U, other than the actual type T).
Explicit constructors are used in classes that consume significant resources, such as memory, build time, etc., to prevent accidental instantiation of such classes. It's up to you to decide if your class is really "heavy" to use an explicit constructor.
It depends on the costs, both semantically and performance. If creating your class is expensive, you should prevent it from accidentally creating an instance. If this is a cheap class to create, then implicit building can greatly simplify the work for an API user.