Operator overload = in c++

Asked

Viewed 90 times

1

I’m having a problem implementing operator overload = in 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 they are heap classes, which have a vector. When I make the impression of this intermediate heap, within the overload, the values are correct, however, after the object is returned to the main, it remains unchanged, with the value that was initially, ie with the value that H3 was before the overload call.

I hope I have been clear about the problem. Thank you From now on.

  • I’m a little rusty on C++ but I don’t think it’s right to return a heap object (allocated with new). What’s more, the idea of returning in Operator= is to return *this. I don’t understand why creating another object.

1 answer

0

The code presented has some problems. Are they:

  1. The return of the allocation operator (operator=) should be, most of the time overwhelming, *this. I won’t go into the details of when this might be different, but by the level of the question I would wager that you were wrong to return 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 attribute operator;

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

That said, I suggest you change your attribution operator 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 of outro for the method escreve() there is no problem, but you must pass the reference of the 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 method escreve() that you have already implemented.

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.