explicit
keyword
https://www.scaler.com/topics/cpp-explicit/
The explicit
keyword is used for single parameter constructors and prevents implicit conversions.
Use with multiple parameter constructor
Starting with C++11, the explicit
keyword can be used for multiple argument constructor provided they have default arguments.
Some examples as seen in CS247.
Suppose we have the 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