explicit keyword in C++
The explicit
keyword is used for single parameter constructors and prevents implicit conversions. First seen in CS247 - Software Engineering Principles.
- Note: Starting with C++11, the
explicit
keyword can be used for multiple argument constructor provided they have default arguments
Suppose we have the following function:
If you don’t have the explicit
keyword, you could do f(247)
. However, if you add the explicit keyword, this won’t work. You need to write
Another example:
Another example:
- This works because
std::string
has a single param constructor which takes in a char*
and is NON-EXPLICIT.
Use Cases
- Preventing unintended object construction
- Avoiding ambiguity in overloaded constructors