Question

I have the following code:

class  Array
{  
   public: 
       int aaa;
       Array():aaa(1){}
      void print()
      {
          cout << aaa << endl;
      }

      Array& operator++()
      {
          aaa++;
          return *this;
      }
      Array operator++(int)
      {
          Array a(*this);
          aaa++;
          return a;
      }
};

I have some questions as follows:

  1. why prefix returns a reference and postfix returns an object? In the book C++ Primer, the author only explained "For consistency with the built-in operators".

  2. Then, I tested the code:

    Array ar;

        (ar++).print(); // print 1
    
        ar.print(); // print 2
    

the output is exactly what I expected. Now I changed the code in the overloading postfix function as:

Array operator++(int)
{
     Array a(*this);
     a.aaa++; // changed this
     return a;
}

I called the test code:

Array ar;
(ar++).print(); // this prints 2
ar.print(); // this prints 1

Why I got such results?

Was it helpful?

Solution

  1. The postfix operator returns an object, not a reference, because it has to return an unchanged version of the current object; it has to return the value before the increment is done. Therefore a new object must be allocated. If you returned a reference, what would it be a reference to?

  2. In your second example, you're creating a new object, incrementing it, and returning it, but you're not changing the original object that the operator was applied to -- this is clearly wrong, so gives wrong results.

OTHER TIPS

While both prefix and postfix operators would intuitively seem to mutate the objects on which they're invoked, they actually have different semantic meanings. The prefix operator takes an an object, applies the increment operation to it, and returns the same object. The postfix operator takes an object, makes a copy of it, applies the increment operator to the orginal, and returns the copy.

It's for this reason that you may have seen various sources discouraging the use of the postfix operator when possible -- because the postfix copy creates a temporary object, it may be less efficient than the prefix operator. For an object that has to maintain a lot of state information, using the postfix operator can be expensive.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top