Is it a good practice to make constructor explicit

This is what I found in a resonse from "Daniel Krügler"

If we would have started to design C++ from today on, there is a good chance, that all constructors and conversion functions were "explicit" by default, but a user could make the "implicit". Alas, the time cannot be turned back and we have to live with the current state. This means that we have to be careful in regard to implicit constructors (except for the copy/move constructor). It is a safer rule to make constructors explicit, where some form of conversion is involved (i.e. any constructor with an argument type U different from the actual type T).


The constructor should be explicit, unless an implicit conversion makes sense semantically (e.g. what is the meaning of converting an int to an A?). Less typing should not be the criterion to guide that decision. Think about readability (which is the main argument for implicit casting) and how well your code is to understand. An implicit cast that is not intuitive will make readers of the code scratch their heads.

P.S.: I cannot seem to come up with a good example right now, so any help is appreciated.


Yes, by default any constructor, which can be called with one argument should be explicit. Following this rule will avoid subtle bugs, which are extremely hard to find.

Of course, there are exceptions to this rule:

  • Implicit conversion might be desireable, if your class has the semantics of a wrapper around the one parameter's type.

  • Copy constructors should not be explicit (otherwise you loose the possibility for pass-by-value calls).

Tags:

C++