explicit (C+)
C++ constructors that have just one parameter automatically perform implicit type conversion. For example, if you pass an int when the constructor expects a string pointer parameter, the compiler will add the code it must have to convert the int to a string pointer. However, you might not always want this automatic behavior.
You can add explicit to the constructor declaration to prevent implicit conversions. This forces the code to either use a parameter of the correct type, or cast the parameter to the correct type. That is, if the cast is not visibly expressed in code, an error will result.
The explicit keyword can only be applied to in-class constructor declarations to explicitly construct an object.
Example
Compiling the following program will produce errors. The code tries to perform an implicit conversion, but use of the explicitkeyword prevents it. To resolve the error, remove the explicit keywords and adjust the code in g.
// spec1_explicit.cpp
// compile with: /EHsc
#include <stdio.h>
class C
{
public:
int i;
explicit C(const C&) // an explicit copy constructor
{
printf_s("\nin the copy constructor");
}
explicit C(int i ) // an explicit constructor
{
printf_s("\nin the constructor");
}
C()
{
i = 0;
}
};
class C2
{
public:
int i;
explicit C2(int i ) // an explicit constructor
{
}
};
C f(C c)
{ // C2558
c.i = 2;
return c; // first call to copy constructor
}
void f2(C2)
{
}
void g(int i)
{
f2(i); // C2558
// try the following line instead
// f2(C2(i));
}
int main()
{
C c, d;
d = f(c); // c is copied
}
Declaring a constructor that has multiple arguments to be explicit has no effect, because such constructors cannot take part in implicit conversions. However, explicit will have an effect if a constructor has multiple arguments and all except one of the arguments has a default value.
See Also
Reference
Change History
Date |
History |
Reason |
---|---|---|
October 2009 |
Revised the introduction. |
Customer feedback. |