c++explicitcppcheckexplicit-constructor

C++ use of explicit suggested by cppcheck


Is using the cast constructor bad? Otherweise why a code quality checker (cppcheck in my case) would constantly suggest to add explicit before single parameter constructors?

What if I want to do

class MyClass {  
 A(int) {}
};

A a = 1;

If I follow the "suggestions" and write

class MyClass {  
 explicit A(int) {}
};

A a = 1; 

would throw an error, but if I use the first I'll have a warning that i've to document to pass the code reviews.


Solution

  • Such implicit class type conversion can be used easily without intention. With this converting constructor every function or member function which accepts MyClass as argument will accept also int. Therefore every int passed to such a function will be converted to a temporary MyClass which will be discarded after the function has finished. Probably not what you want.