Reputation: 1763
I am trying to instantiate an object and delete it afterwards, what am I doing wrong?
default:
//Instantiate object of the ErrorHandler class
errPtr = new ErrorHandler();
//Print the error message to the console screen
errPtr->showError("Invalid input, please select option 1 or 2, and press enter.");
delete errPtr;
errPtr->showError("hello"); //This line is being executed normally like object still exist.
break;
My question is how come I can call the showError(); method after deleting it's object?
Upvotes: 1
Views: 541
Reputation: 1541
There is nothing wrong with the way you are instantiating and deleting - what is happening is down to the way memory is allocated (or more appropriately in this case deallocated).
When you free()
(delete
in c++) heap memory, it simply flags it as available - it doesn't clear your pointer or the memory it used to point to; doing so would decrease performance particularly if your object was quite large. Everything stays intact in memory until something else uses it.
Because errPtr is used directly after your delete
, the object is still in memory.
C++ doesn't stop you from using a pointer after it's deleted, but it's a very bad idea to do so as your pointer is now pointing towards memory which could potentially be used by something else.
Basically what you are doing wrong here is using a pointer after the memory it's pointing to is freed. Once you delete your object it's down to you to not reference it - you have to trust that the memory is now free once you have called delete
.
Upvotes: 3
Reputation: 1
errPtr->showError("hello"); //This line is being executed normally like object still exist.
It's simply undefined behavior though.
Anything can happen if you are dereferencing a pointer that was delete
d before, including the seemingly correct behavior.
Upvotes: 4