Previous section   Next section

Imperfect C++ Practical Solutions for Real-Life Programming
By Matthew Wilson
Table of Contents
Appendix B.  "Watch That Hubris!"


B.1. Operator Overload

One of the first things new C++ programmers get turned onto is operator overloading, which is ironic because it's probably one of the most pervertible parts of the language.

My first string class had an enormous public interface, of which the following extract details only the very worst bits:



class DLL_CLASS String // Exports all members indiscriminately


  : public BaseObject // A polymorphic string . . . ?


{


  . . .


  // Makes the string nInitLen length, filled with cDef


  String &Set(int nInitLen, char cDef = '\0');


  . . .


  Bool   SetLowerAt(int nAt); // Returns true if was upper


  Bool   SetUpperAt(int nAt); // Returns true if was lower


  . . .


  String &operator =(int nChopAt); // Set length to nChopAt


  . . .


  String &operator +=(int nAdd); // Increase length by nAdd


  . . .


  String &operator -=(int nReduce); // Reduce length by nReduce


  // Reduces length to last matching character


  String &operator -=(char cChopBackTo);


  . . .


  // Rotate (with wrap) the string contents left/right


  String &operator >>=(int nRotateBy);


  String &operator <<=(int nRotateBy);


  . . .


  String &operator --();    // Makes all characters lower case


  String &operator --(int); // Makes all characters lower case


  String &operator ++();    // Makes all characters upper case


  String &operator ++(int); // Makes all characters upper case


  . . .


  // Returns a local static with converted value


  static String NumString(long lVal);


  . . .


  operator const char *() const; // Implicit conversion to c-str


  . . .


  operator int() const; // Implicit conversion, returning length


  . . .


  // Returns an element by value


  const char operator [](int nIndex) const;


  . . .


  String &operator ^=(char cPrep);           // Prepend char


  String &operator ^=(const char *pcszPrep); // Prepend string


  . . .


};



It'd be hard to imagine doing a worse job—a case of can be done, will be done. I'll be terribly saddened if your reaction to this was anything but violently antipathetic. Amazingly, I managed to get the addition operators correct: defined as free functions and implemented in terms of operator +=() (see section 25.1.1).



String operator +(const String &String1,const String &String2);


String operator +(const String &String1,const char *pcszAdd);


String operator +(const char *pcszAdd,const String &String2);


String operator +(const String &String1,char cAdd);


String operator +(char cAdd,const String &String1);



Scarily, recent postings on one of the newsgroups I follow, from a couple of people who are generally impressively cluey, said they thought "operator ++() means make upper" was a good idea! Let's hope they just hadn't thought it through.


      Previous section   Next section