Search code examples
c++operator-overloadingcompiler-warningspostfix-operator

How to properly overload postfix increment operator?


Is there a way to modify this code so that I do not receive a warning when compiling ? Also, couldn't this code potentially result in a segfault since the memory it is going to access to retrieve the value of x in main got deallocated at the end of the operator function call?

class A {

  int x; /* value to be post-incremented */

  public:

  A() {  /* default constructor */
  }

  A( A & toCopy ) {   /* copy constructor */
    x = toCopy.x;
  }

  A & operator++(int) {  /* returns a reference to A */

    A copy( *this );         /* allocate a copy on the stack */
    ++x;

    return copy;            /* PROBLEM: returning copy results in a warning */

  }                         /* memory for copy gets deallocated */

}; /* end of class A */

int main() {

  A object;
  object.x = 5;

  cout << (object++).x << endl;   /* Possible segfault ? */

}

Solution

  • You need to return a value (not a reference):

    A operator++(int) { /*...*/ }
    

    this will resolve the compiler warning and you won't end up with a dangling reference.