Namespaces
Variants
Views
Actions

Difference between revisions of "cpp/language/explicit"

From cppreference.com
< cpp‎ | language
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

 
 
C++ language
General topics
Flow control
Conditional execution statements
if
Iteration statements (loops)
for
range-for (C++11)
Jump statements
Functions
Function declaration
Lambda function expression
inline specifier
Dynamic exception specifications (until C++17*)
noexcept specifier (C++11)
Exceptions
Namespaces
Types
Specifiers
const/volatile
decltype (C++11)
auto (C++11)
constexpr (C++11)
consteval (C++20)
constinit (C++20)
Storage duration specifiers
Initialization
Expressions
Alternative representations
Literals
Boolean - Integer - Floating-point
Character - String - nullptr (C++11)
User-defined (C++11)
Utilities
Attributes (C++11)
Types
typedef declaration
Type alias declaration (C++11)
Casts
Memory allocation
Classes
Class-specific function properties
explicit (C++11)
static

Special member functions
Templates
Miscellaneous
 

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.

Example

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
}