Namespaces
Variants
Views
Actions

explicit specifier

From cppreference.com
< cpp‎ | language
Revision as of 15:12, 22 September 2014 by Zingam (Talk | contribs)

 
 
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.

A constructor with a single-parameter constructor that is declared without the function specifier explicit is called a conversion constructor.

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 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
}