C++ explicit Keyword
The explicit
keyword in C++ is used to prevent unintended implicit conversions or automatic type casting for constructors and conversion operators. It is particularly useful in ensuring type safety and avoiding subtle bugs caused by unintended object creation through implicit conversions.
The explicit
keyword can be applied to constructors and conversion operators to enforce that they are only invoked explicitly.
Syntax
</>
Copy
explicit ClassName(parameters);
explicit operator target_type() const;
- explicit
- The keyword used to prevent implicit conversions.
- ClassName
- The name of the class to which the explicit constructor or operator belongs.
- parameters
- The parameters for the explicit constructor.
- target_type
- The type to which the explicit conversion operator applies.
Examples
Example 1: Using explicit
Constructor
In this example, we will learn how an explicit
constructor prevents implicit conversions.
</>
Copy
#include <iostream>
using namespace std;
class MyClass {
public:
explicit MyClass(int value) {
cout << "Constructor called with value: " << value << endl;
}
};
int main() {
MyClass obj1(10); // Explicit call
// MyClass obj2 = 20; // Error: Implicit conversion is not allowed
return 0;
}
Output:
Constructor called with value: 10
Explanation:
- The constructor is marked
explicit
, so it prevents implicit conversions. - Calling the constructor with
MyClass obj1(10)
works because it is explicit. - Uncommenting
MyClass obj2 = 20;
results in a compilation error because implicit conversion is not allowed.
Example 2: Using explicit
Conversion Operator
In this example, we will learn how to use an explicit
conversion operator.
</>
Copy
#include <iostream>
using namespace std;
class MyClass {
int value;
public:
MyClass(int val) : value(val) {}
explicit operator int() const {
return value;
}
};
int main() {
MyClass obj(42);
// int x = obj; // Error: Explicit conversion required
int x = static_cast<int>(obj); // Explicit conversion
cout << "Value: " << x << endl;
return 0;
}
Output:
Value: 42
Explanation:
- The conversion operator
operator int()
is markedexplicit
. - An explicit cast, such as
static_cast<int>(obj)
, is required to convert the object to anint
. - Implicit conversions like
int x = obj;
are disallowed, ensuring safer and more predictable code.
Key Points about explicit
Keyword
- The
explicit
keyword prevents unintended implicit conversions for constructors and conversion operators. - It improves code readability and avoids subtle bugs caused by implicit type casting.
- Starting from C++11,
explicit
can be applied to conversion operators. - An
explicit
constructor or operator must be invoked explicitly, such as through direct calls orstatic_cast
.