5
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?

Steephen
  • 14,645
  • 7
  • 40
  • 47

2 Answers2

4

I think {77,5,42} has the implicit type of std::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.

mavam
  • 12,242
  • 10
  • 53
  • 87
1

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++?

Community
  • 1
  • 1
Support Ukraine
  • 42,271
  • 4
  • 38
  • 63