So I have this code:
struct Foo {
Foo() { cout << "default\n"; }
Foo(const long long) { cout << "implicit\n"; }
};
struct Bar {
Bar(const short param) : param(param) {}
operator long long() const { return static_cast<long long>(param); }
const short param;
};
I would have thought that Foo foo = Bar(13)
would have used my implicit cast and then the converting constructor. But it errors:
error: conversion from
Bar
to non-scalar typeFoo
requested
This works fine though: Foo foo(Bar(13))
. Why is my implicit cast used for explicit converting construction, but not for implicit converting construction?
The rules I got from https://en.cppreference.com/w/cpp/language/copy_initialization say:
The result of the conversion, which is a prvalue expression if a converting constructor was used, is then used to direct-initialize the object
Firstly the implicit conversion from
Bar
tolong long
, and the one fromlong long
toFoo
are both user-defined conversion.Foo foo = Bar(13);
perform copy initialization, the compiler will try to convertBar
toFoo
implicitly. Two implicit conversions are required, i.e. convertingBar
tolong long
and then convertinglong long
toFoo
. But only one user-defined conversion is allowed in one implicit conversion sequence.Foo foo(Bar(13));
performs direct initialization. The constructors ofFoo
would be examined and the best match is selected by overload resolution. Only one implicit user-defined conversion (fromBar
tolong long
) is required; after thatFoo::Foo(long long)
is called to constructfoo
directly.