When designing a public API, is it a good practice to make the constructor as 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 shall I allow implicit conversion, to allow user to call my API with less typing?
The constructor should be explicit, unless an implicit conversion makes sense semantically (e.g. what is the meaning of converting an
intto anA?). 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.