Assignment Operator Overloading Question

In summary, the conversation is about a program that demonstrates the use of operator overloading for assignment. The code includes a member function that returns a reference to NumberArray and uses the dereference operator to return data stored in a pointer. The conversation also touches on the use of the delete operator to free up memory and the potential for memory leaks if not used correctly. The need for returning a reference and deleting memory on the heap is explained in the context of the program and its potential variations in array sizes. Overall, the conversation provides insight into the importance of properly managing memory in a program.
  • #1
MinusTheBear
22
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
  • #2
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.
 
  • #3
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.
 
  • #4
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.
 
  • #5
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.
 

FAQ: Assignment Operator Overloading Question

What is assignment operator overloading?

Assignment operator overloading is a technique in object-oriented programming where the standard assignment operator (=) is redefined for a user-defined data type. This allows for custom behavior when assigning values to objects of that data type.

Why is assignment operator overloading useful?

Assignment operator overloading allows for more intuitive and readable code by enabling objects to be assigned values in a way that makes sense for that specific data type. It also helps to prevent errors and improve efficiency by avoiding unnecessary copying of objects.

How is assignment operator overloading implemented?

Assignment operator overloading is implemented by creating a member function for the class that defines the user-defined data type. This function is typically named "operator=" and takes in a reference to another object of the same type. The function then performs the necessary operations to assign the values from the given object to the current object.

What are the guidelines for overloading the assignment operator?

To properly overload the assignment operator, it is important to follow certain guidelines. These include returning a reference to the current object, handling self-assignment, and properly managing memory for dynamically allocated objects. It is also recommended to make the function a friend of the class to allow access to private members.

What are the potential pitfalls of assignment operator overloading?

Some potential pitfalls of assignment operator overloading include creating unexpected behavior for users, violating the principle of least astonishment, and causing confusion or errors when used with other operators or functions. It is important to carefully design and test the overloaded operator to avoid these issues.

Similar threads

Replies
53
Views
4K
Replies
1
Views
8K
Replies
23
Views
2K
Replies
31
Views
2K
Replies
18
Views
2K
Replies
89
Views
5K
Replies
3
Views
2K
Back
Top