Overloading ++ and –

Overloading the increment (and decrement) operator creates a slight problem: there are two version of each operator,
as they may be used as postfix operator (e.g., x++) or as prefix operator (e.g., ++x).
Suppose we define a class iterator whose members can be used to visit the elements of an array. The iterator object
will return a pointer to an element of the array, and the increment operators will change the pointer to the next
element. A partially defined bvector class is:

class bvector
{
public:
  bvector(int *vector, unsigned size):vector(vector),current(vector),finish(vector + size){}
  int *begin()
  {
    return(current = vector);
  }
  operator int *() const
  {
    return (current);
  }
  // increment and decrement operators: see the text
private:
  int *vector, *current, *finish;
};

In order to privide this class with an overloaded increment operator, the following overloaded operator++() can be
designed:

int *bvector::operator++()
{
  return (++current);
}

As current is incremented before it is returned, the above overloaded operator++() clearly behaves like the prefix
operator. However, it is not possible to use the same function to implement the postfix operator, as overloaded
functions must differ in their parameterlists. To solve this problem, the convention is adopted to provide the postfix
operator with a (abstract) int parameter. So, the postfix increment operator can be designed as follows:

int *bvector::operator++(int)
{
  return (current++);
}

In situations where the function operator++() is called explicitly, a dummy int argument may be passed to the function
to indicate that the postfix version is required. If no argument is provided, the prefix version of the operator is used.
E.g.,

bvector *bvp = new bvector(intArray, 10);
bvp->operator++(1); // postfix operator++()
bvp->operator++() // prefix operator++()
Share and Enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Add to favorites
  • LinkedIn
  • Propeller
  • Reddit
  • StumbleUpon
  • Technorati
  • Twitter
  • Yahoo! Bookmarks

Related posts:

  1. Overloading operator delete(void *)
  2. Overloading operator[]()
  3. Overloading operator new(size_t)
  4. C++ Basics Tutorial – Lesson 7
  5. C++ Advanced Tutorial – Lesson 9

Leave a Reply