Difference between revisions of "cpp/language/explicit"
From cppreference.com
Line 46: | Line 46: | ||
int nb1 = b2; // Error: implicit conversion from B to int | int nb1 = b2; // Error: implicit conversion from B to int | ||
int nb2 = static_cast<int>( b2 ); // OK: explicit cast | int nb2 = static_cast<int>( b2 ); // OK: explicit cast | ||
+ | |||
+ | B b4 = static_cast<B>(1); // OK: explicit conversion from int to B | ||
} | } | ||
}} | }} |
Revision as of 11:54, 22 September 2014
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.
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 B A a2 ( 2 ); // OK: explicit constructor call A a3 { 3 }; // OK: explicit constructor call int na1 = a1; // OK: implicit conversion from B to int int na2 = static_cast<int>( a1 ); // OK: explicit cast 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 }