explicit specifier
From cppreference.com
Specifies constructors and (since C++11) conversion operators that don't allow implicit conversions or copy-initialization.
Syntax
explicit class_name ( params ) | |||||||||
explicit operator type ( ) (since C++11) | |||||||||
1) specifies that this constructor is only considered for direct initialization
2) specifies that this user-defined conversion function is only considered for direct initialization
Explanation
explicit on a constructor with multiple arguments has no effect, since such constructors cannot take part in implicit conversions. However, for the purpose of implicit conversion, explicit will have an effect if a constructor has multiple arguments and all but one of the arguments has a default value.
A constructor with a single-parameter constructor that is declared without the function specifier explicit is called a conversion constructor.
This section is incomplete |
Example
Run this code
struct A { A(int) {} operator int() const { return 0; } }; struct B { explicit B(int) {} explicit operator int() const { return 0; } }; int main() { // A has no explicit ctor / conversion, everything is fine A a1 = 1; // OK: implicit conversion from int to A A a2(2); // OK: explicit constructor call A a3 { 3 }; // OK: explicit constructor call int na1 = a1; // OK: implicit conversion from A to int int na2 = static_cast<int>(a1); // OK: explicit cast A a4 = (A)1; // OK: explicit conversion from int to A B b1 = 1; // Error: implicit conversion from int to B B b2(2); // OK: explicit constructor call B b3 { 3 }; // OK: explicit constructor call int nb1 = b2; // Error: implicit conversion from B to int int nb2 = static_cast<int>(b2); // OK: explicit cast B b4 = static_cast<B>(1); // OK: explicit conversion from int to B B b5 = (B)1; // OK: explicit conversion from int to B }