Hello all! I've been working with a book, learning about overloading operators. I went a veered off the path and went ahead and made "itsAge" into a pointer and dynamically allocated memory for the pointer in the class constructor. The thing is, when I try to delete the pointer in the destructor, the program crashes. If I can't delete the pointer in the destructor, then where do I delete it?
You can (and should) delete itsVal in your destructor. Your code is failing because you've forgotten to write an assignment operator. Add something like this:
Normally you would check for self-assignment, but since you don't have to re-allocate the memory, this will work. Otherwise, when you do something like this:
a = i++;
What you're really doing is using the compiler's synthesised assignment operator on the temporary object that the postfix ++ operator returns. The synthesized assignment operator copies the pointer, but the object is destroyed as soon as the assignment is completed. Its destructor is called, freeing the memory, but a is left pointing to the memory that it just freed. What's more, the old pointer was replaced, but the memory it pointed to wasn't freed, so you have a memory leak too.
^ I obviously knew that I was using the assignment operator but I didn't know how I could use it without overloading it. Thanks for clearing that up!
What you're really doing is using the compiler's synthesised assignment operator on the temporary object that the postfix ++ operator returns.
My book failed to mention the compiler's synthesized assignment operator, but I assumed there was something happening that I hadn't learned yet.
Maybe I just tried to do more than I should be doing with my current knowledge of c++... Haha, this happens a lot to me. I should just stick to copying what the author wrote for now, lol.
Its destructor is called, freeing the memory, but a is left pointing to the memory that it just freed. What's more, the old pointer was replaced, but the memory it pointed to wasn't freed, so you have a memory leak too.
^ Would overloading the assignment operator and using it correctly fix all those errors?