Assignment Operator Overloading Question

  • Context:
  • Thread starter Thread starter MinusTheBear
  • Start date Start date
  • Tags Tags
    Assignment Operator
Click For Summary

Discussion Overview

The discussion revolves around the implementation of the assignment operator overloading in C++, specifically focusing on the code snippet provided by a participant. The participants explore the mechanics of memory management, pointer usage, and the rationale behind returning a reference in the operator overload function.

Discussion Character

  • Technical explanation
  • Conceptual clarification
  • Debate/contested

Main Points Raised

  • One participant questions the necessity of returning a reference in the assignment operator and seeks clarification on where the returned value is utilized.
  • Another participant explains that returning a reference ensures the object remains valid until it goes out of scope, which is important for assignment operators.
  • Concerns are raised about memory management, particularly regarding the deletion of the old memory pointed to by aPtr to avoid memory leaks when new memory is allocated.
  • Some participants discuss the implications of not deleting the old memory, noting that it could lead to crashes if the sizes of the arrays differ.
  • There is a discussion about whether it is safe to overwrite memory on the heap and the potential risks associated with varying array sizes.
  • One participant suggests that while it is possible to rewrite memory, careful management is necessary to avoid writing beyond allocated limits.
  • Another participant mentions that while optimizations could be made when the right object has fewer elements, the current approach is simpler and always correct.

Areas of Agreement / Disagreement

Participants express varying levels of understanding regarding memory management and the implications of the assignment operator's implementation. There is no consensus on the necessity of certain lines of code, and the discussion remains unresolved regarding the best practices for memory handling in this context.

Contextual Notes

Participants highlight the importance of memory allocation and deallocation when dealing with pointers and dynamic arrays, emphasizing the need for careful management to prevent memory leaks and crashes. The discussion reflects a range of experiences with C++ programming, particularly in relation to pointers and operator overloading.

Who May Find This Useful

This discussion may be useful for individuals learning C++ programming, particularly those interested in operator overloading, memory management, and pointer usage in dynamic arrays.

MinusTheBear
Messages
22
Reaction score
0
Hey everyone. First I am new to programming (so my vocabulary and skills are not very proficient with C++), and I'm learning operator overloading. I have questions about line 1 and lines 5-8 of this code.
Mod note: changed quote tags to code tags to preserve indentation.
C:
NumberArray& NumberArray :: operator=(const NumberArray &right)
{
    if (this != &right)
    {
      if (arraySize > 0)
      {
          delete [] aPtr; // this is a pointer defined in the class
      }
      arraySize = right.arraySize;
      aPtr = new double[arraySize];
      for (int index = 0; index < arraySize; index++)
      {
        aPtr[index] = right.aPtr[index];
      }
    }
    return *this;
}

This is sample of a member function in a much larger program. The goal of the program is to demonstrate that during assignment you have to use operator overloading as opposed to a construction operator in initialization. The point of it is if I assigned the following:

NumberArray a, b;
a = {1, 2, 3}
b = {2}
a = b

That a should be 'a' should now be assigned '2'. And this code accomplishes that. However, in line 1 it's returning a reference to NumberArray., and then on line 16, it's using the dereference operator to return the data of stored in the pointer 'this.' My question is, why should I return a reference, and where is this returning the value to?

Secondly, on line 7, why should I want to delete this from the heap? If I reassign my values in lines 11-15, doesn't this just overwrite the memory since I'm using the pointer in those lines? So it doesn't appear to me that I'm creating any memory leaks.

I'm asking this because I've removed all of these from the code and it still runs fine.

Thanks.
 
Last edited by a moderator:
Technology news on Phys.org
Typical reasons for returning a reference are one wants to make sure the returned object actually exists and stays defined until the object goes out of scope. These are pretty useful things to have the complier guarantee for an assignment operator.

The memory is deleted on line 7 because aPtr is overwritten on line 10. This means we will loose the address of the old memory after the call to new which is a leak. The test code sequence given works with lines 7 and 10 removed because a has more elements than b. If you remove lines 7 and 10 and change the test assignment to b=a the program will crash.
 
eq1 said:
Typical reasons for returning a reference are one wants to make sure the returned object actually exists and stays defined until the object goes out of scope. These are pretty useful things to have the complier guarantee for an assignment operator.

The memory is deleted on line 7 because aPtr is overwritten on line 10. This means we will loose the address of the old memory after the call to new which is a leak. The test code sequence given works with lines 7 and 10 removed because a has more elements than b. If you remove lines 7 and 10 and change the test assignment to b=a the program will crash.

So is this line essentially checking that if aPtr has been defined, then it will have some assigned memory value on the heap? Thus if it has assigned memory value, it wants to delete it since were defining new memory on the heap of an array that may potentially be a different size in line 10?

In other words I'll have two different memory locations on the heap of differing sizes, where one of them I am no longer using? I guess what it boils down to is why can't I just rewrite this memory on the heap? Is it because my array sizes may vary?

Sorry, my book I'm using just went from fairly easy concepts (for me) to grasp to going concepts on crack since it hit the pointers chapter.
 
MinusTheBear said:
In other words I'll have two different memory locations on the heap of differing sizes, where one of them I am no longer using? I guess what it boils down to is why can't I just rewrite this memory on the heap? Is it because my array sizes may vary?
You can rewrite memory on the heap, no problem, but you need to be careful not to write beyond the limits of this memory, in either direction. If the array sizes are different (or could be), that's a good reason for doing separate heap allocations and being careful to free the memory when it's no longer used.
 
MinusTheBear said:
Is it because my array sizes may vary?

Yes, that is why.

If the object right has more elements than can fit in the memory pointed to by aPtr then we need to create a new memory region which is large enough. If right has less elements then one doesn't necessarily have to do the new/delete operations on aPtr, and in some cases that optimization could make sense, but this way is a lot easier and is always correct so that's probably why the author selected it.
 

Similar threads

  • · Replies 1 ·
Replies
1
Views
8K
Replies
53
Views
5K
  • · Replies 23 ·
Replies
23
Views
3K
  • · Replies 31 ·
2
Replies
31
Views
3K
Replies
10
Views
2K
  • · Replies 18 ·
Replies
18
Views
3K
  • · Replies 89 ·
3
Replies
89
Views
6K
Replies
5
Views
2K
  • · Replies 3 ·
Replies
3
Views
3K
Replies
5
Views
6K