C++ Keywords - explicit

Last Updated: 2022-02-08

Implicit conversions allow an object of one type (called the source type) to be used where a different type (called the destination type) is expected, such as when passing an int argument to a function that takes a double parameter.

The explicit keyword can be applied to a constructor or a conversion operator, to ensure that it can only be used when the destination type is explicit at the point of use, e.g., with a cast. This applies not only to implicit conversions, but to list initialization syntax:

class Foo {
  explicit Foo(int x, double y);

void Func(Foo f);
Func({42, 3.14}); // Error

Use the explicit keyword for conversion operators and single-argument constructors. There is no need to mark the default, copy, or move constructors explicit.