What does the explicit keyword do in C++, and when should it be used?

I’ve seen the explicit keyword used in C++ class constructors, but I’m not entirely sure what it means or why it’s needed.

From what I understand, it prevents implicit conversions, but could someone explain how explicit works in C++, maybe with a simple example?

Also, in what situations is using the C++ explicit keyword strongly recommended or considered best practice?

1 Like

Oh, I’ve definitely had my fair share of frustrations with this! The explicit keyword in C++ is a lifesaver. It prevents the compiler from making automatic conversions, which can lead to bugs that are hard to spot. I learned this the hard way when I had a constructor that took a single int parameter. Without explicit, C++ was converting plain integers into my class objects automatically, which led to some pretty weird behavior in my functions.

Here’s an example to illustrate:

class MyClass {
public:
    expl

icit MyClass(int x); // avoids automatic conversion
};

Without the explicit keyword, something like someFunc(42) could accidentally create a MyClass instance, if someFunc accepts MyClass. So, I make it a point to use explicit with single-argument constructors unless I specifically want implicit conversions.

1 Like

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.

I can totally relate to that! I once spent hours wondering why a string was being treated as a custom type in an entirely unrelated part of my code. The culprit? I forgot to add explicit to my constructor. That’s when I truly realized the power of this simple keyword.

To simplify it, here’s a great rule of thumb: if your constructor takes one parameter, and you don’t want implicit conversion, always use explicit. It can save you a ton of debugging time.

class Token {
public:
    explicit Token(std::string type);
};

If I’d added explicit from the start, I would’ve caught the error right away. So now, it’s my default unless I’m specifically writing wrapper classes where conversion is expected. It’s such a small keyword, but it has a massive impact.