Assignment Operator Overloading Question

AI Thread Summary
The discussion centers on understanding operator overloading in C++, specifically regarding the assignment operator for a class managing dynamic memory. The code provided demonstrates how to safely assign one instance of `NumberArray` to another while managing memory to prevent leaks. Key points include the importance of returning a reference to the object in the assignment operator to ensure the object remains valid after the assignment. The deletion of the existing memory pointed to by `aPtr` before allocating new memory is crucial to avoid memory leaks, especially when the sizes of the arrays may differ. If the existing memory is not deleted, it could lead to losing access to that memory, resulting in a leak. The discussion emphasizes that while it is technically possible to overwrite memory on the heap, doing so without proper management can lead to issues, particularly when array sizes vary. The approach taken in the code ensures safety and correctness in memory management during assignments.
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.
 
Dear Peeps I have posted a few questions about programing on this sectio of the PF forum. I want to ask you veterans how you folks learn program in assembly and about computer architecture for the x86 family. In addition to finish learning C, I am also reading the book From bits to Gates to C and Beyond. In the book, it uses the mini LC3 assembly language. I also have books on assembly programming and computer architecture. The few famous ones i have are Computer Organization and...
I have a quick questions. I am going through a book on C programming on my own. Afterwards, I plan to go through something call data structures and algorithms on my own also in C. I also need to learn C++, Matlab and for personal interest Haskell. For the two topic of data structures and algorithms, I understand there are standard ones across all programming languages. After learning it through C, what would be the biggest issue when trying to implement the same data...
Back
Top