Operator overload = in c++

I'm having a problem implementing operator = overhead on a heap class.

  Heap& Heap::operator=(const Heap& outro){
  printf("chamei atribuição\n");
  this->escreve();

  Heap *h = new Heap(outro);
  printf("htemp\n");
  h->escreve();

  return *h;
}

For example: I call h3 = h1 in main, where the same are heap classes, which have a vector. When I print this intermediate heap, within the overload, the values are correct, however, after the object is returned to main, it remains unchanged, with the value that was initially, that is, with the value that h3 was before the call of overload.

I hope I've been clear about the problem. Thank you right now.

Author: Victor Lelis, 2020-04-02

1 answers

The code presented has some problems. They are:

  1. The Return of the assignment operator (operator=) should be, in the overwhelming majority of cases, *this. I'm not going to go into the details of when this might be different, but by the level of the question I'd bet you got it wrong by returning a reference to another object;

  2. Your code is probably leaking memory. Based on your question I see no point in making an allocation of a new object in the assignment operator;

  3. Within the assignment operator usually the values of the object outro are assigned to the object this. This is as simple as assigning one variable to another: membro = outro.membro;

That said, I suggest changing your assignment operator's code to:

Heap& Heap::operator=(const Heap& outro){
    // Aqui você atribui os membros do objeto "outro" aos membros do objeto "this".
    membro1 = outro.membro1;
    membro2 = outro.membro2;
    membro3 = outro.membro3;
    membro4 = outro.membro4;
    return *this;
}

If you want to pass the responsibility of "copying" the variables from outro to the method escreve() there is no problem at all, but you should pass the reference from source object. Example:

Heap& Heap::operator=(const Heap& outro){
    printf("chamei atribuição\n");
    this->escreve(outro);
    return *this;
}

Of course for this to work you must first modify or overwrite the escreve() method you have already implemented.

PS: the use of the" prefix " this-> is optional.

 0
Author: Fernando Silveira, 2020-04-02 12:13:40