Operator overload in C ++

1
#define TAMSEC 59
#define TAMMIN 59
#define TAMHOURS 23

using namespace std;

class Time{
private:
int hours,
    minutes,
    seconds;
public:
Time(int hours = 0, int minutes = 0, int seconds = 0);
/**Sobre carga operador <<**/
friend ostream& operator << (ostream& out, const Time &obj);
/**Sobrecarga operador (Pre incremento ++)**/
Time& operator ++();
/**Sobrecarga operador (Pos incremento ++)**/
Time operator ++(int);
 };

 /**Sobrecarga operador (Pre incremento ++)**/
Time& Time::operator ++(){
seconds ++;
if(seconds > TAMSEC){
    minutes ++;
    seconds = 0;
    if(minutes > TAMMIN){
        minutes = 0;
        hours ++;
        if(hours > TAMHOURS)
            hours = 0;
    }
}
return *this;
}
/**Sobrecarga operador (Pos incremento ++)**/
Time Time::operator++(int){
Time aux = Time(*this);
seconds ++;
if(seconds > TAMSEC){
    minutes ++;
    seconds = 0;
    if(minutes > TAMMIN){
        minutes = 0;
        hours ++;
        if(hours > TAMHOURS)
            hours = 0;
    }
  }
  return aux;
  }

I was developing the overload of operators of the post and pre-increment of my Time class, my doubt is when I do the pos increment, at the beginning I wanted to return the reference of my object (* aux) that I created within the member function before increase its attributes, but it does not leave me, so I had to return the object itself. Why can not I return the reference of my aux object?

   Time& Time::operator++(int){
   Time aux = Time(*this);
   seconds ++;
   if(seconds > TAMSEC){
      minutes ++;
      seconds = 0;
      if(minutes > TAMMIN){
        minutes = 0;
        hours ++;
        if(hours > TAMHOURS)
          hours = 0;
      }
   }
   return *aux;
   }
    
asked by Jorge Gonzalez 30.10.2016 в 16:40
source

2 answers

3
int& func()
{
  int variable=5;
  return variable;
}

Let's analyze the previous function:

A local variable is created, assigned a value and a reference to it is returned. The problem? That when leaving the function the variable is lost, then the reference returned is not valid.

This same concept is applicable to your code. Never you must return a reference to a local variable because the reference's lifetime will be longer than the lifetime of the variable.

In your example, however, it is worth doing return *this; because, as you know, *this points to the current object, which will remain alive after leaving the post-increment function.

Greetings

    
answered by 30.10.2016 / 17:37
source
1

It would be similar to:

T *p = new T;
T &r = *p;
delete p;
// Hacer uso de r.

A local variable of a function is automatically removed when the function is terminated.

I suggest:

Time operator ++(int) { Time aux = *this; ++*this; return(aux); }

(online). Avoid repetition in the source code. Because it is online, allow the compiler to remove aux when the return value is not used, and apply better copy epsilon when the return value is used.

    
answered by 30.10.2016 в 19:09