DDS
DDS

Reputation: 2478

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.

Upvotes: 3

Views: 1786

Answers (2)

Peter
Peter

Reputation: 2320

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.

Upvotes: 5

bolov
bolov

Reputation: 75825

C++ Core Guidelines

C.46: By default, declare single-argument constructors explicit

Reason

To avoid unintended conversions.

Example, bad

class String {
public:
    String(int);   // BAD
    // ...
};

String s = 10;   // surprise: string of size 10

Exception

If you really want an implicit conversion from the constructor argument type to the class type, don't use explicit:

class Complex {
public:
    Complex(double d);   // OK: we want a conversion from d to {d, 0}
    // ...
};

Complex z = 10.7;   // unsurprising conversion

See also: Discussion of implicit conversions

Upvotes: 6

Related Questions