skip to content

In C++, why does send(30) compile when send takes a const Connection& and Connection has a constructor Connection(int), and what does explicit change?

level: middleimportance: must knowfreq 70%

answer

  1. converting constructor
  2. copy-initialization allows it
  3. direct-initialization and casts only
  4. explicit(bool) since C++20

basics

~20 s

A constructor not marked explicit is a converting constructor, so Connection(int) lets the compiler build a temporary Connection from 30. Marking it explicit keeps it for direct-initialisation and casts but removes the implicit conversion, so send(30) stops compiling.

solid answer

~40 s

The standard says a constructor that is not `explicit` specifies a conversion from its parameter types to its class. With `Connection(int timeoutMs)`, `send(30)` silently creates a temporary `Connection(30)`, and even `send(2.5)` compiles by chaining a standard conversion `double` to `int` with the user-defined one. Copy-initialisation such as `Connection c = 5;` takes the same path. An `explicit` constructor still constructs objects, but only where direct-initialisation or a cast is written: `Connection c(30)`, `Connection{30}`, `static_cast<Connection>(30)`. It also stops copy-list-initialisation such as `send({"db", 5432})` for multi-argument constructors. The usual rule is to mark single-argument constructors `explicit` unless the conversion is genuinely value-preserving and expected, as with `std::string` from `const char*`. C++20 added `explicit(bool)` so wrapper templates can be explicit exactly when the wrapped conversion is.

code

cpp · 18 lines
cpp
#include <cstdio>

class Connection {
public:
    Connection(int timeoutMs) : timeoutMs_(timeoutMs) {}   // converting constructor
    int timeout() const { return timeoutMs_; }
private:
    int timeoutMs_;
};

void send(const Connection& conn) { std::printf("timeout=%d\n", conn.timeout()); }

int main() {
    send(30);          // compiles: a temporary Connection(30) is built silently
    send(2.5);         // compiles too: double -> int -> Connection
    Connection c = 5;  // copy-initialization through the same conversion
    send(c);
}

go deeper

for a junior

Recall that a one-argument constructor allows implicit conversion unless it is marked explicit, and that explicit still allows direct construction.

for a middle

Distinguish copy-initialisation from direct-initialisation, show how a standard conversion can chain with the constructor, and how braces extend this to multi-argument constructors.

for a senior

Apply explicit by default to single-argument constructors of meaningful types, and use explicit(bool) in C++20 wrappers to mirror the wrapped conversion.

for a principal

Set the team default, explicit unless a conversion is value-preserving and expected, and decide how to roll it out without breaking existing callers.

## Converting constructors In C++ any constructor callable with one argument and not marked `explicit` doubles as an **implicit conversion**. The standard puts it generally: a constructor that is not explicit specifies a conversion from the types of its parameters, if any, to the type of its class. With ```cpp class Connection { public: Connection(int timeoutMs) : timeoutMs_(timeoutMs) {} // ... }; void send(const Connection& conn); ``` all of these compile: - `send(30);` builds a temporary `Connection(30)` and binds the reference to it. - `send(2.5);` chains a standard conversion (`double` to `int`, which truncates to 2) with the user-defined conversion; Clang only warns about the literal changing value. - `Connection c = 5;` is **copy-initialisation** through the same conversion. Each line is legal and probably a bug: a bare number is being treated as a whole connection. Running the snippet prints `timeout=30`, `timeout=2` and `timeout=5`. ## What explicit changes An `explicit` constructor constructs objects just like any other, but only where the code asks for it. The standard's note lists the contexts: direct-initialisation syntax or an explicit cast. | Expression | Non-explicit `Connection(int)` | `explicit Connection(int)` | |---|---|---| | `Connection c(30);` | OK | OK, direct-initialisation | | `Connection c{30};` | OK | OK, direct-list-initialisation | | `auto c = Connection(30);` | OK | OK, the cast-like functional notation is explicit | | `static_cast<Connection>(30)` | OK | OK, explicit cast | | `Connection c = 30;` | OK | error: no viable conversion | | `send(30);` | OK | error: no matching function | | `send({30});` | OK | error: copy-list-initialisation | With `explicit`, Apple clang 21 reports `error: no matching function for call to 'send'` for both calls and `error: no viable conversion from 'int' to 'Connection'` for the copy-initialisation. ## Multi-argument constructors and braces `explicit` matters beyond one-argument constructors. Since C++11, braces let a multi-argument constructor convert too: `send({"db", 5432})` copy-list-initialises the parameter. If the constructor is `explicit Endpoint(const char* host, int port)`, that call fails and the caller must write `send(Endpoint{"db", 5432})`. An `explicit` default constructor likewise rejects `Endpoint e = {};` while still allowing `Endpoint e;` and `Endpoint e{};`. ## Choosing when to use it A widely used default: 1. Mark **every single-argument constructor** `explicit`. 2. Drop `explicit` only when the conversion is **value-preserving and expected** by readers, as in `std::string` from `const char*`, `std::string_view` from `std::string`, or a `Duration` from another unit of time. 3. Never rely on implicit conversion for **types that carry meaning beyond their representation**: a timeout, a port and a file descriptor are all `int`, which is exactly why a `Connection` should not accept a bare one. Copy and move constructors are normally left non-explicit; making them explicit breaks copy-initialisation and returning by value in surprising ways. ## explicit(bool) in C++20 Generic wrappers want to be implicitly convertible exactly when the wrapped type is. Before C++20 that needed two constrained constructor templates; C++20 added a conditional form: ```cpp template <class T> struct Wrapper { template <class U> explicit(!std::is_convertible_v<U, T>) Wrapper(U&& u) : value(static_cast<U&&>(u)) {} T value; }; ``` `Wrapper<std::string> w = "text";` compiles because `const char*` converts implicitly to `std::string`. Compiled with `-std=c++17`, Clang accepts the code only as an extension and warns `explicit(bool) is a C++20 extension`. ## Constructors that take one argument by accident A constructor converts whenever it can be **called with one argument**, not only when it declares exactly one parameter. The standard's own example declares `X(const char*, int = 0)` and then writes `X b = "Jessie";`, which calls `X("Jessie", 0)`. So a review for missing `explicit` should cover: - constructors with **one parameter**; - constructors whose **other parameters all have default arguments**, such as `Connection(int timeoutMs, int retries = 3)`; - **constructor templates** taking a forwarding reference, which can convert from almost anything; - multi-parameter constructors that callers might reach through **braces**, as in `send({"db", 5432})`. Compiler warnings such as `-Wconversion` look at conversions between arithmetic types, so they do not flag an implicit conversion through a constructor; this is a review or static-analysis question. ## Conversion operators The same keyword applies to conversion functions such as `explicit operator bool() const`, the other direction of conversion; how those behave in conditions is covered with casts and conversions.

  • Does an explicit C++ constructor still allow Connection c{30}; and static_cast<Connection>(30)?
    Yes. `explicit` only removes the constructor from implicit conversions, copy-initialisation and copy-list-initialisation. Direct-initialisation with parentheses or braces, functional notation such as `Connection(30)`, and explicit casts all still call it, because the programmer named the target type.
  • Why does std::vector's size constructor matter here, and is it explicit?
    `std::vector<T>` has a constructor taking a `size_type` count, and it is declared `explicit`. Without that, a function taking `const std::vector<int>&` could be called with a plain integer, silently building a vector of that many elements. The standard library marks such count constructors explicit for exactly the reason a `Connection(int)` should be.

  • explicit is needed only on constructors with exactly one parameter.
  • An explicit constructor cannot be called with brace initialization.
  • Implicit conversion through a constructor happens only for exact type matches.
  • explicit also prevents static_cast from using the constructor.
  • Marking copy constructors explicit is a good default.

Assumes C++20 or later for explicit(bool); plain explicit constructors behave the same since C++11.