Explicit keyword applied to operator instead of constructor

  • A+

In the class below,

Why would you make the operators explicit. I thought that explicit was to prevent implicit calling of constructors?

 class Content             { public:   virtual ~Content() = 0;  virtual explicit operator float&();  virtual explicit operator long long&();  virtual explicit operator std::string&() } 


You would use it if you wanted a Content object never to be implicitly converted to (say) a float. This could happen in the following way:

 void f( float f );  ....  Content c;  f( c );      // conversion from Content to float 

Without the explicit qualifier, the conversion happens implicitly; with it, you get a compilation error.

Silent, implicit conversions can be the source of a lot of confusion and/or bugs, so it's generally better to make the operators explicit , or probably better yet to provide named functions, such as ToFloat, which tell the reader exactly what is going on.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: