What is the explicit keyword and why use it?
Short answer
explicit prevents a constructor or conversion operator from being used for implicit conversions, requiring direct/explicit invocation. It avoids surprising conversions—like a class accidentally constructed from an int in a function call—that cause ambiguity or bugs.
Advertisement
AModel answer
explicit prevents a constructor or conversion operator from being used for implicit conversions, requiring direct/explicit invocation. It avoids surprising conversions—like a class accidentally constructed from an int in a function call—that cause ambiguity or bugs. Best practice marks single-argument constructors explicit unless implicit conversion is genuinely desired.
struct Meters { explicit Meters(double); };
void f(Meters);
// f(3.0); // error, good
f(Meters(3.0)); // explicit, clearReal-world example
explicit on a Distance(double) constructor prevents a raw double from silently becoming a Distance.
Likely follow-ups
- Which conversions does it block? | When would you allow implicit conversion?
Related topics