Classes and class hierarchies
C.46
By default, declare single-argument constructors explicit
Reason
To avoid unintended conversions.
Example, bad
class String {
public:
String(int); // BAD
// ...
};
String s = 10; // surprise: string of size 10
Exception
If you really want an implicit conversion from the constructor argument type to the class type, don't use explicit:
class Complex {
public:
Complex(double d); // OK: we want a conversion from d to {d, 0}
// ...
};
Complex z = 10.7; // unsurprising conversion
See also: Discussion of implicit conversions
Note
Copy and move constructors should not be made explicit because they do not perform conversions. Explicit copy/move constructors make passing and returning by value difficult.
Enforcement
(Simple) Single-argument constructors should be declared explicit. Good single argument non-explicit constructors are rare in most code bases. Warn for all that are not on a "positive list".