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?

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.