12.1 Conversions

12.1.1 Do not declare implicit user defined conversions

A user defined conversions can occur through the use of a conversion operator or a conversion constructor (a constructor that accepts a single argument). A compiler can invoke a single user defined conversion in a standard conversion sequence, but only if the operator or constructor is declared without the explicit keyword. It is better to declare all conversion constructors and operators explicit.

#include <cstdint>
   
class C
{
public:
C (const C&);                      // @@+ Compliant: copy constructor +@@
C ();                              // @@+ Compliant: default constructor +@@
C (int32_t, int32_t);              // @@+ Compliant: more than one non-default argument +@@
                                               
explicit C (int32_t);              // @@+ Compliant +@@
C (double);                        // @@- Non-Compliant -@@
C (float f, int32_t i = 0);        // @@- Non-Compliant -@@
C (int32_t i = 0, float f = 0.0);  // @@- Non-Compliant: default constructor, -@@
                                   // @@-   but also a conversion constructor -@@
operator int32_t () const;         // @@- Non-Compliant -@@
explicit operator double () const; // @@+ Compliant +@@
};

References

  • HIC++ v3.3 – 3.2.3
  • HIC++ v3.3 – 3.1.10
  • HIC++ v3.3 – 3.1.11

Click here for references