Assignment operator overloading
I am having a hard time understanding the assignment operator overloading in a class that has a pointer as its member attribute. My question is: why does it make a memory leak if you do not delete the pointer before reassigning the value of the right hand side object? For example, there is a class called Number that has a pointer, itsNum, to an integer that is dynamically allocated (just as an example). Here is the code for assignment operator:
Also, another question is if pointers of *this and rhs point to the same address (even though two objects are distinct), doesn't deleting itsNum create a problem?
Number& Number::operator=(const Number& rhs)
if (this != &rhs)
itsNum = new int;
*itsNum = *(rhs.itsNum);