Skip to content

Latest commit

 

History

History
108 lines (65 loc) · 1.91 KB

CppExplicit.md

File metadata and controls

108 lines (65 loc) · 1.91 KB

 

 

 

 

 

 

explicit is a keyword to disable converting constructors.

 

 

 

 

 

Example

 

The example below will not compile, due to the explicit keyword written in the constructor of Test:

 


struct Test {   explicit Test(const int x) {} }; int main() {   Test t_i = 0; }

 

The line in main needs to call a converting constructor, because an int is not a Test (that is: they are different data types).

 

 

 

 

 

 

 

 

 

 

 

  1. Herb Sutter. Exceptional C++. ISBN: 0-201-61562-2. Item 20, page 71, top guideline :'Watch out for hidden temporaries created by implicit conversions. One good way to avoid this is to make constructors explicit when possible, and avoiding writing conversion operators'
  2. Bjarne Stroustrup. The C++ Programming Language (4th edition). 2013. ISBN: 978-0-321-56384-2. Chapter 16.4. Advice. page 479: '[5] By default declare single-argument constructors explicit'