Aug 01, 2004

Refresher course on conversion operators...

The August 2004 issue of The C/C++ Users Journal has a great article by Michael H. Manov entitled “The Perils of operator const char*().” This article reiterates Item 5 of More Effective C++ by Scott Meyers, viz. be wary of user-defined conversion functions.

The article starts off by sampling a simple class, such as:

class StringClass {
 char *str;
// ... Normal stuff
  // Conversion Operator
  operator const char*() { return str; }

And then shows the following example program:

void function() {
 StringClass aString;
  // ... more stuff
  delete aString;

This program not only compiles on standard compliant compilers but results in a core dump, as str is deleted twice. To compile the line delete aString, a compiler will automatically use the operator const char *() operator to convert aString into a pointer value. I mention standard compliant compilers, as Microsoft's Visual C++ Version 6 would not allow you to delete a constant pointer, however, the standard permits this behaviour.

As Scott told us, these functions end up being called when you do not want or expect it to be called, and this usually leads to a hard to diagnose program, and so Michael experienced. This article is a great refresher course.

Filed In