Hi!
I created an object (Jack the Pig) in the dynamic memory (heap).
Because it is a pointer, I can erase it by delete.
So I deleted Jack the Pig, but it is not deleted, because Jack->Row function still is working (writes out Rooooow).

Why can Jack->Row function still work, if before it I deleted Jack the Pig object?

#include "StdAfx.h"
#include <iostream>

class Pig
{
public:
	Pig(){};
	~Pig() {std::cout << "Pig is killed!\n";}
	void Rof() {std::cout << "Roooooof!\n";}
};

int main()
{
Pig* Jack;
Jack = new Pig;
Jack->Rof();
delete Jack;
std::cout << "-----------\n";
Jack->Rof();

return 0;
}

Ok here is an analogy I head and I will try it out:

Imagine you picked a hotel, and then you bought a room, so they gave you the key to that room. You take out your bible, read it and then put it inside your drawer. Next morning you have to leave because your time is up. You pack everything up and leave, but you left your bible in the drawer and you forgot to hand in your key. Next day you remember that you left your bible in the drawer and you remember you still have the key to that room. Now you know your not allowed to go to that room because your time is up, but you figure, what the hell I'll just see if this key works and try to get my book back. Surprisingly, your key does work and what do you know your book is still in the drawer. Why would anyone remove it anyways? They probably didn't need that space yet, so they just left it as it, which is why your book was still there.

Now use the above analogy to the problem you've shown. You picked a hotel, in your case, its called Pig. You rented a room, in your case its room Jack. Now you have a key to that room, the pointer. You do stuff in that room, in your case call Rof(), and your day has expired, you called delete on Jack, now you come back to that room, and what do you know your key( pointer ) is still working, even though your not allowed technically. Usually, a good hotel( IDE ) would make some type of alarm, but some do not. And so you realize that your key still 'works' and because your 'Rof' still 'works', why? Because the hotel didn't really need that space right now, in your case it didn't need the memory right now, so they left it as is.

And that is a simplified reason on why you get the above output. From the above you should get that, even if it seems to work, realize that your not allowed to do it and that you shouldn't rely on this behavior, because good hotels( good IDE) will cause an alarm to go off, and your off to jail( you get fired ).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.