`explicit` — C++ Keyword

`explicit` — C++ Keyword

The explicit keyword in C++: prevents implicit conversions and copy-list initializations.

How to use this reference page

Use reference pages to confirm names, categories, nearby facilities, and the constraints that matter before writing or reviewing code.

  • Scan the top of the page first to identify the primary types, functions, or algorithm families involved.
  • Use the nearby-page links when your question is really about a companion header, related algorithm family, or broader subsystem.
  • Validate tricky behavior with a small compileable example before relying on memory for details like invalidation, ordering, allocation, or lifetime rules.

explicit

Prevents a constructor or conversion function from being used in implicit conversions. Since C++20, explicit can take a boolean constant expression for conditional explicitness.

Syntax

explicit ClassName(params);
explicit operator Type() const;
explicit(constant-expression) ClassName(params);  // C++20 conditional

Example

#include <print>

struct Dollars {
    explicit Dollars(double amount) : amount_(amount) {}
    // Without explicit: Dollars d = 3.5; would compile silently
    double amount_;
};

struct Meters {
    double value;
    explicit Meters(double v) : value(v) {}
    explicit operator double() const { return value; }
};

void spend(Dollars d) {
    std::println("spending ${:.2f}", d.amount_);
}

int main() {
    // spend(9.99);          // error: no implicit conversion
    spend(Dollars{9.99});    // OK: explicit construction

    Meters m{5.0};
    // double d = m;         // error: explicit conversion operator
    double d = static_cast<double>(m);  // OK: explicit cast
    std::println("{}", d);
}

Notes

Example in practice

int main() {
    // Pick one facility from this reference page.
    // Write the smallest program that exercises its main precondition,
    // complexity rule, or lifetime constraint before scaling up.
    return 0;
}