The explicit function specifier controls unwanted implicit type conversions. Basically, it tells the compiler that only explicit call to this constructor is allowed.
For example, if there is a buffer class whose constructor
Buffer(int size)
takes the size of the buffer in bytes, and you don't want the compiler to quietly turn
int
s into
Buffer
s. So to prevent that, you declare the constructor with the
explicit
keyword:
class Buffer
{
explicit Buffer(int size);
...
}
That way,
void useBuffer(Buffer& buf);
useBuffer(4);
becomes a compile-time error. If you want to pass a temporary
Buffer
object, then do the following
useBuffer(Buffer(4));
This will prevent the compiler from surprising you with unexpected conversions.