class P {
public:
explicit P( int a, int b, int c) {
std::cout<<"calling explicit constructor"<<"\n";
}
};
int main() {
P z {77,5,42}; // OK
P w = {77,5,42}; // ERROR due to explicit (no implicit type conversion allowed)
}
I think {77,5,42} has the implicit type of std::initialization_list<int>. If that is the case what is not causing the failure of construction of variable z?
I think
{77,5,42}has the implicit type ofstd::initialization_list<int>
{77,5,42} by itself has no type. If you write auto x = {77, 5, 42} then x is of type initializer_list. Your example type P has an explicit constructor. Effectively, this means you have to write:
P w = P{77, 5, 42}
Or better:
auto w = P{77, 5, 42}
If that is the case what is not causing the failure of construction of variable
z?
The construction does not fail because you are initializing it explicitly: P x{a, b, c} does not perform an implicit conversion of any kind, but simply uses the uniform initialization syntax to invoke the (explicit) constructor of P.
The compiler is trying to do implicit conversion by finding a constructor that can match the
= {77,5,42};
part.
However, the constructor it finds, is marked explicit so it can't be used for implicit conversion. Consequently you'll get an error.
This may be of interest: What does the explicit keyword mean in C++?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With