Exactly! The explicit
keyword is all about writing clear and predictable code. It stops the compiler from using that constructor for automatic conversions, making sure your types behave exactly as you intend. This is particularly crucial in modern C++ design, where clarity and safety are top priorities.
For instance:
class Distance {
public:
explicit Distance(double meters);
};
Now, if you try to do something like Distance d = 5.0;
, it won’t compile unless you explicitly use Distance d(5.0);
. It forces you to be intentional, which makes the code much easier to maintain. My advice: use explicit
by default on single-argument constructors unless implicit conversion is genuinely needed.