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
void f(Rational num) {
...
}
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
f(Rational{247});
Another example:
class Node {
Node* next;
int data;
public:
Node(int data): data{data}, next{nullptr} {}
}
void q(Node n) {
...
}
q(4); // doesn't complain, because there is no explicit keyword
Another example:
void f(std::string s) {
...
}
f("Hello World"); // This doesn't complain, even though "Hello World" has type char*
- This works because
std::string
has a single param constructor which takes in achar*
and is NON-EXPLICIT.
Use Cases
- Preventing unintended object construction
class MyString {
public:
explicit MyString(const char* str) {
// Constructor code
}
};
void ProcessString(const MyString& str) {
// Process the string
}
// Without explicit:
ProcessString("Hello"); // Implicit conversion
// With explicit:
ProcessString(MyString("Hello")); // Explicit conversion required
- Avoiding ambiguity in overloaded constructors
class Point {
public:
explicit Point(int x) {
// Constructor code
}
Point(int x, int y) {
// Constructor code
}
};
Point p1 = 10; // Error: No implicit conversion
Point p2(10); // OK: Explicit conversion
Point p3 = Point(10); // OK: Explicit conversion required
Point p4(10, 20); // OK: Explicit conversion