Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explicit constructor and initialization with std::initializer_list

Tags:

c++

c++11

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?

like image 554
Steephen Avatar asked May 09 '15 16:05

Steephen


2 Answers

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.

like image 80
mavam Avatar answered Oct 13 '22 07:10

mavam


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

like image 1
Support Ukraine Avatar answered Oct 13 '22 07:10

Support Ukraine