explicit specifier

From cppreference.com
< cpp‎ | language
 
 
C++ language
General topics
Flow control
Conditional execution statements
Iteration statements
Jump statements
Functions
function declaration
lambda function declaration
function template
inline specifier
exception specifications (deprecated)
noexcept specifier (C++11)
Exceptions
Namespaces
Types
decltype specifier (C++11)
Specifiers
cv specifiers
storage duration specifiers
constexpr specifier (C++11)
auto specifier (C++11)
alignas specifier (C++11)
Initialization
Literals
Expressions
alternative representations
Utilities
Types
typedef declaration
type alias declaration (C++11)
attributes (C++11)
Casts
implicit conversions
const_cast conversion
static_cast conversion
dynamic_cast conversion
reinterpret_cast conversion
C-style and functional cast
Memory allocation
Classes
Class-specific function properties
explicit (C++11)
static
Special member functions
Templates
class template
function template
template specialization
parameter packs (C++11)
Miscellaneous
Inline assembly
 

Specifies constructors and (since C++11) conversion operators that don't allow implicit conversions or copy-initialization.

[edit] 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

[edit] 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;
    A a2 ( 2 );
    A a3 { 3 };
    int na1 = a1;
    int na2 = static_cast<int>( a1 );
 
    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
}