Implicit vs. Explicit

Conversion constructors can be implicit (which is the default), or explicit. The implicit conversion constructor is called any time the compiler needs a Time object, but finds a double that it can convert. Consider this fragment of code:

Time bed_time(23, 30);      // 11:30
bed_time = 5.2;             // WHAAAAT?

You would expect that line 2 would be a syntax error, but, surprisingly, it is not. Instead, the conversion constructor is silently (implicitly) called, and bed_time is changed to 5:12 am. Probably not what you expected.

You can add explicit as a modifier to the prototype to prevent this:

explicit Time(double hours);  // 7.51 -> 7:35

The keyword explicit only goes in the class definition. It is not repeated in the .cpp file. Sometimes, as you'll see when you cover symmetric overloaded operators in CS 250, you'll want to allow implicit conversion. For instance the string(const char*) constructor is not explicit. Most of the time, however, explicit is preferred.