C++ Reference ยท Keywords and Statements
The explicit specifier
Reference for C++ explicit: blocking implicit conversions through single-argument constructors and conversion operators, explicit(bool) in C++20, and examples.
explicit stops the compiler from using a constructor or conversion operator implicitly. Without it, a constructor that can be called with one argument also acts as an implicit conversion: a function taking a Meters will happily accept a plain double. That is convenient for types like std::string, but dangerous for most others.
With explicit, the conversion must be spelled out: Meters m{5.0} or static_cast<Meters>(5.0). Since C++11 the same applies to conversion operators (explicit operator bool()), and since C++20 you can make it conditional with explicit(constant-expression).
struct Meters { explicit Meters(double v) : value(v) {} double value; };
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.
Syntax
explicit ClassName(params); // constructor explicit operator Type() const; // conversion function (C++11) explicit(constant-expression) declaration; // conditional (C++20)
| Part | Description |
|---|---|
constant-expression |
A bool constant. If true the declaration is explicit; explicit alone means explicit(true) |
Usage notes
- Default to
explicitfor every constructor callable with one argument (including ones with defaults on the rest, and variadic templates). Drop it only when the conversion is natural and lossless, likestd::stringfrom a C string. - It affects copy-initialization (
Meters m = 5.0;, function arguments,return 5.0;), not direct initialization (Meters m{5.0};,Meters m(5.0);). - Before C++11 it only mattered for one-argument constructors. Now it also matters for multi-parameter constructors in copy-list-initialization:
Point p = {1, 2};fails ifPoint(int, int)is explicit. - An
explicit operator boolcan still be used where the language performs a contextual conversion to bool:if,while,forconditions,!,&&,||and?:. It cannot silently become anint, which avoids the old safe-bool problems. expliciton copy or move constructors is legal but rare; it breaks pass-by-value andreturnof that type in some forms. Avoid it.- A conversion operator with
explicittakes part in direct-initialization andstatic_cast, sostatic_cast<bool>(handle)works. explicit(bool)lets generic wrappers (std::pair,std::optional,std::tuple) mirror the convertibility of what they wrap.- Deduction guides can also be declared
explicit.