Search code examples
c++operator-overloadingpostfix-operatorprefix-operator

How overloaded postfix operator works?


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?


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.