- #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.
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.
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: