19.8.4.  More About explicit Conversion Constructors

[ fromfile: types.xml id: moreconversion ]

Section 2.12 has explicit conversion constructors. Following is another example that uses one.

Suppose that, for some reason, you needed to write your own String class.[110] You might produce a class definition with several constructors such as these:

        class String {
          String();                // Creates an empty String of length 0
          String(const char* str); // Converts a char array to a String
          explicit String(int n);  // Creates length n String, filled 
                                   // with spaces
          ... other member functions - but not constructors ...
        };
        

Describe the String objects str1 and str2 produced by the following client code lines.

          ...
          String str1, str2;        // construct two empty strings
          str1 = "A";
          str2 = 'A';
          ...
        

It would not be illogical for you to expect str1 and str2 to be quite similar after those assignments: both short String objects, each containing a single character 'A'. However, depending on how you implemented the conversion constructor (i.e., how the terminating null char is handled), str1 will indeed contain a single 'A' and perhaps a null. But the str2 assignment is a completely different story. If the keyword explicit were removed, str2 would become a length 65 String filled with spaces. That is because char 'A' would be promoted to the int 65 (the ASCII code for 'A') so that the third constructor could be (implicitly) called.

Specifying that the third constructor is explicit is a good way to avoid such a misunderstanding. Doing so causes the str2 assignment to generate a compile error; i.e., the third constructor cannot be called implicitly – it can only be called explicitly. Hence, the String class would have no way to handle that line of code and the compiler would report an error.



[110] Voice of screaming Sgt. Major: "So, QString not good enough for you, eh?"