In C++, the explicit keyword is used to prevent implicit conversions from a given type to another type. It is used to ensure that a constructor or conversion function is called only when an explicit conversion is requested, and not during implicit conversions.
For example, let’s consider a class called MyInt that represents an integer value. We can define a constructor that takes an int value as its argument, like this:
class MyInt {
public:
MyInt(int value) : m_value(value) {}
private:
int m_value;
};
Now suppose we have a function that takes a MyInt object as its argument, like this:
void printMyInt(MyInt myInt) {
std::cout << myInt << std::endl;
}
We can call this function with an integer value, like this:
int x = 5;
printMyInt(x);
This code will compile and run without errors, even though we are passing an integer value to a function that expects a MyInt object. This is because the MyInt constructor that takes an integer value is being called implicitly to convert the integer value to a MyInt object.
To prevent this kind of implicit conversion, we can use the explicit keyword to make the constructor explicit:
class MyInt {
public:
explicit MyInt(int value) : m_value(value) {}
private:
int m_value;
};
With this modification, the code that calls printMyInt with an integer value will no longer compile, because the implicit conversion from int to MyInt is no longer allowed. Instead, we have to create a MyInt object explicitly, like this:
int x = 5;
MyInt myInt(x); // explicit conversion
printMyInt(myInt);
The explicit keyword can also be used with conversion functions, which are functions that allow an object of one type to be converted to another type. By marking a conversion function as explicit, we can ensure that the conversion is only done when an explicit conversion is requested, and not during implicit conversions.
For example:
class MyInt {
public:
explicit operator int() const {
return m_value;
}
private:
int m_value;
};
void printInt(int x) {
std::cout << x << std::endl;
}
int main() {
MyInt myInt(5);
printInt(myInt); // Error! Conversion from MyInt to int is not implicit.
printInt(static_cast<int>(myInt)); // OK! Explicit conversion to int.
return 0;
}
In this example, we have defined a conversion function that allows a MyInt object to be converted to an int value. However, we have marked the conversion function as explicit, so that it can only be used during explicit conversions. As a result, the call to printInt(myInt) will not compile, but we can use an explicit cast to convert the MyInt object to an int value and pass it to printInt instead.