explicit specifier - cppreference.com

From cppreference.com

Syntax

explicit(1) explicit (expression)(2) (since C++20)2) The explicit specifier may be used with a constant expression. The function is explicit if and only if that constant expression evaluates to true.

(since C++20)The explicit specifier may only appear within the decl-specifier-seq of the declaration of a constructor or conversion function(since C++11) within its class definition.

Notes

A constructor with a single non-default parameter(until C++11) that is declared without the function specifier explicit is called a

converting constructor

.

Both constructors (other than

copy

/

move

) and user-defined conversion functions may be function templates; the meaning of explicit does not change.

A ( token that follows explicit is always parsed as part of the explicit specifier:

structS{explicit(S)(constS&);// error in C++20, OK in C++17explicit(operatorint)();// error in C++20, OK in C++17};(since C++20)Feature-test macroValueStdFeature

__cpp_conditional_explicit

201806L

(C++20)conditional explicitKeywords

explicit

Example

Run this code

structA{A(int){}// converting constructorA(int,int){}// converting constructor (C++11)operatorbool()const{returntrue;}};structB{explicitB(int){}explicitB(int,int){}explicitoperatorbool()const{returntrue;}};intmain(){Aa1=1;// OK: copy-initialization selects A::A(int)Aa2(2);// OK: direct-initialization selects A::A(int)Aa3{4,5};// OK: direct-list-initialization selects A::A(int, int)Aa4={4,5};// OK: copy-list-initialization selects A::A(int, int)Aa5=(A)1;// OK: explicit cast performs static_castif(a1){}// OK: A::operator bool()boolna1=a1;// OK: copy-initialization selects A::operator bool()boolna2=static_cast<bool>(a1);// OK: static_cast performs direct-initialization// B b1 = 1; // error: copy-initialization does not consider B::B(int)Bb2(2);// OK: direct-initialization selects B::B(int)Bb3{4,5};// OK: direct-list-initialization selects B::B(int, int)// B b4 = {4, 5}; // error: copy-list-initialization does not consider B::B(int, int)Bb5=(B)1;// OK: explicit cast performs static_castif(b2){}// OK: B::operator bool()// bool nb1 = b2; // error: copy-initialization does not consider B::operator bool()boolnb2=static_cast<bool>(b2);// OK: static_cast performs direct-initialization[](...){}(a4,a5,na1,na2,b5,nb2);// suppresses “unused variable” warnings}See also

converting constructor

initialization

copy initialization

direct initialization