skip to content

In C++, what does `explicit` block on a constructor and on `operator bool`, and where does `explicit operator bool` still convert?

level: middleimportance: must knowfreq 60%

answer

  1. converting constructors and conversion functions
  2. copy-initialization vs direct-initialization
  3. contextual conversion to bool
  4. if, !, &&, ||, ?:

basics

~20 s

An explicit constructor is not used for copy-initialization or implicit conversions, only for direct-initialization and casts. An explicit operator bool converts only in explicit casts and contextual conversions such as if conditions, !, && and ||.

solid answer

~40 s

Without `explicit`, a one-argument constructor and a conversion function each let a class join implicit conversions: `void dispatch(PluginHandle)` would accept any `void*`, and a handle with `operator bool` would compile in `h + 1`. An `explicit` constructor is used only for direct-initialization (`PluginHandle h{p}`) and explicit casts; copy-initialization, parameter passing and `return p;` stop compiling, and since C++11 that applies to multi-argument constructors through `= {a, b}` too. An `explicit operator bool` converts only in explicit casts and in contextual conversions: `if`, `while`, `for` conditions, the operands of `!`, `&&`, `||`, the first operand of `?:`, and `static_assert`. So `if (h)` works, `bool b = h;` does not. C++20 adds `explicit(bool)` for conditional explicitness.

code

cpp · 23 lines
cpp
#include <cstdio>

struct PluginHandle {
    explicit PluginHandle(void* raw) : raw_(raw) {}
    explicit operator bool() const { return raw_ != nullptr; }
    void* raw() const { return raw_; }
private:
    void* raw_;
};

void dispatch(PluginHandle h) { std::puts(h ? "live" : "null"); }  // ?: converts contextually

int main() {
    int ctx = 0;
    PluginHandle h{&ctx};               // direct-initialization: allowed
    dispatch(PluginHandle{&ctx});       // conversion spelled at the call site
    if (h && h.raw() == &ctx) std::puts("ok");   // && converts contextually
    bool b = static_cast<bool>(h);      // explicit conversion: allowed
    std::printf("%d\n", b);
    // dispatch(&ctx);                  // error: no matching function for call to 'dispatch'
    // PluginHandle h2 = &ctx;          // error: no viable conversion from 'int *' to 'PluginHandle'
    // bool bad = h;                    // error: no viable conversion from 'PluginHandle' to 'bool'
}

go deeper

for a junior

Recall that explicit stops implicit conversions through a constructor or conversion operator, and that if (h) still works with explicit operator bool.

for a middle

Separate copy-initialization from direct-initialization and list the contextual conversion sites where explicit operator bool still applies.

for a senior

Review wrappers around C handles for missing explicit, and show the overload-resolution or arithmetic bug an implicit bool conversion invites.

for a principal

Adopt explicit-by-default for single-argument constructors and conversion operators as a lint-enforced rule, with documented exceptions for value-like types.

## Implicit conversions through user-defined types C++ lets a class take part in **implicit conversions** in two ways: - a **converting constructor**: a constructor callable with one argument, `PluginHandle(void* raw)`, lets a `void*` become a `PluginHandle` wherever one is expected; - a **conversion function**: `operator bool() const` lets a `PluginHandle` become a `bool` wherever one is expected. At most one user-defined conversion may appear in an implicit conversion sequence, but one is enough to surprise. A function `void dispatch(PluginHandle)` would accept any `void*`, and `handle + 1` would compile by converting the handle to `bool` and then to `int`. ## What `explicit` blocks on a constructor Marking the constructor `explicit` removes it from **copy-initialization** and from implicit conversion sequences. With `explicit PluginHandle(void* raw)`: | Form | Compiles? | |---|---| | `PluginHandle h(&ctx);` or `PluginHandle h{&ctx};` | yes, direct-initialization | | `static_cast<PluginHandle>(&ctx)` | yes, an explicit conversion | | `PluginHandle h = &ctx;` | no, copy-initialization | | `dispatch(&ctx);` | no, parameter passing is copy-initialization | | `return &ctx;` from a function returning `PluginHandle` | no | Since C++11 `explicit` also applies to constructors with several parameters: `return {lo, hi};` or `Range r = {1, 2};` fails with "chosen constructor is explicit in copy-initialization", while `Range r{1, 2};` compiles. ## What `explicit` does on `operator bool` An `explicit operator bool() const` (C++11) is used only for **explicit conversions** and **contextual conversions to `bool`**. The contexts where the language converts contextually include: - the conditions of `if`, `while`, `for` and `do`; - the operands of `!`, `&&` and `||`; - the first operand of `?:`; - `static_assert` and the `noexcept( )` specifier's operand. So `if (h)`, `while (!h)` and `h && ready` compile, as does `static_cast<bool>(h)`, but `bool b = h;`, `return h;` from a `bool` function and `int n = h + 1;` do not. Before C++11, classes used the "safe-bool idiom" (a conversion to a pointer-to-member type) to get this behaviour; `explicit operator bool` replaced it, and the standard library's smart pointers and streams use it. ## Conditional `explicit` (C++20) C++20 adds `explicit(bool)`: the constructor is explicit when a constant expression is `true`. A wrapper template can then be implicit for safe conversions and explicit for narrowing ones in a single declaration, for example `explicit(!std::is_convertible_v<U, T>)`, which the standard library uses for types such as `std::pair` and `std::optional`. ## The bug `explicit` prevents Suppose the handle had a plain `operator bool() const` and the code also contains `void set_log_level(int level)`. The call `set_log_level(handle)` compiles: the handle converts to `bool` through the user-defined conversion, then `bool` promotes to `int`, so the log level becomes `0` or `1` depending on whether the plugin is loaded. Nobody wrote a conversion; the compiler assembled one standard conversion after one user-defined conversion, which an implicit conversion sequence allows. Likewise, without an `explicit` constructor, `dispatch(nullptr)` would construct a handle from a null pointer constant and call into the plugin layer. Both mistakes become compile errors once the two conversions are `explicit`, and the intended uses (`if (handle)`, `PluginHandle{raw}`) keep working. ## A plugin handle done right When porting a C plugin interface that passes `void*` around, wrapping the pointer in a small class is common, and both conversions should be explicit: 1. `explicit PluginHandle(void*)`, so a random `void*`, or a `nullptr` constant, does not become a handle by accident at a call site; 2. `explicit operator bool() const`, so the handle tests naturally in `if` without decaying into an integer in arithmetic or overload resolution; 3. any conversion back to `void*` for the C side as a named member function such as `raw()`, rather than an implicit conversion operator. Designing user-defined conversion operators in general (when to provide one at all, member versus non-member, symmetry) is the subject of the material on overloaded operators; the rules above are about which conversions the language then performs on its own. ## How it reads in review - A single-argument constructor without `explicit` is a question: is an implicit conversion from that argument really wanted? - A conversion operator without `explicit` that returns `bool` or an integer is almost always a bug waiting for an arithmetic expression. - A constructor whose later parameters all have default arguments is still callable with one argument, so it converts implicitly too; it needs `explicit` just as much.

  • Why do `std::unique_ptr` and the iostreams use `explicit operator bool`?
    Both want `if (p)` and `if (stream)` to work without letting the object convert to `bool` and then to an integer in arithmetic, comparisons or overload resolution. An explicit conversion operator gives exactly the contextual conversions and nothing else, which the pre-C++11 safe-bool idiom approximated with a pointer-to-member conversion.
  • Does `explicit` stop `PluginHandle h = PluginHandle(&ctx);`?
    No. The right-hand side names the type, so the explicit constructor is called by an explicit functional-notation conversion; the copy-initialization then initializes `h` from a `PluginHandle` prvalue, which since C++17 constructs `h` directly. `explicit` only blocks conversions the compiler would insert on its own.

  • explicit operator bool cannot be used in an if condition.
  • explicit only matters for constructors with exactly one parameter.
  • An explicit constructor cannot be called with brace initialization.
  • Two user-defined conversions can chain in one implicit conversion.
  • static_cast cannot call an explicit constructor.