Operator Overloading continued

A few rules:

  1. Most of the C++ operators can be overloaded:
  2. +    -    *    /    %    ^    &    |
    ~    !    =    <    >    +=   -=   *=
    /=   %=   ^=   &=   |=   <<   >>   >>=
    <<=  ==   !=   <=   >=   &&   ||   ++
    --   ->*  ,    ->   []   ()   new  delete
    

    However, the following cannot be overloaded:

    .    .*   ::   ?:   sizeof
  3. It is not possible to change the number of operands that an operator takes

  4. It is not possible to create new operators

  5. The meaning of an operator for a built-in type cannot be changed

  6. The functions for (), [], ->, or = MUST be declared as class members. For the other operators, they can be member or non-member functions.

  7. Overloading the + and = operators, does not imply that += has been overloaded.

  8. Two functions must be written to overload ++ (and --), since it can be used as either a post or pre increment (or decrement).

  9. The prefix version is handled as any other prefix operator would be handled:

    ++object;    becomes    object.operator++();   //for member functions
    
                            operator++(object);    //for non-member functions

    The postfix version presents a challange because it MUST have a different signature than the prefix version. To accomplish this, the postfix version's header has a dummy integer argument:

    object++;    becomes    object.operator++(0);   //for member functions
    
                            operator++(object, 0);    //for non-member functions
    
    
    X X::operator++()                 //pre-increment
      {
      i++;
      return *this;
      }
    
    X X::operator++(int)    //post-increment
      {
      X temp = *this;       //or X temp( i );
      
      i++;                  //increment the one pointed to by this pointer
      
      return temp;          //but return the non-incremented one
                            //(where the initial value is saved)
      }
    
    
    In a program:
    
    X d(18);
    
    cout << "Pre-increment:\n"
         << "   d is " << d
         << "\n ++d is " << ++d
         << "\n   d is " << d;
    
    
    cout << "\n\nPost-increment:\n"
         << "   d is " << d
         << "\n d++ is " << d++
         << "\n   d is " << d;
    
    
    Will produce:
    
    Pre-increment:
       d is 18
     ++d is 19
       d is 19
    
    Post-increment:
       d is 19
     d++ is 19
       d is 20