Zipster: LOL...man, I must have been really tired.
I see what you are saying now. Thanks for correcting me!
quote:Original post by kuphryn
You made it look like in:
ClassX *CX = new ClassX;
"new ClassX" *is not* deleted in:
delete CX;
It is just "CX" that is gone.
That is where I am confused from your explanation.
"CX" is a pointer that refers to "new ClassX." The C++ "delete" expression takes a pointer and destroys the object it refers to - so long as the object itself was allocated with "new". Together, new and delete allow you to manage the lifetime of the object manually, as opposed to simply declaring objects whose lifetimes are determined by language rules (i.e., their scope in the program).
The following two examples are basically identical in terms of object construction/destruction, because of where the new and delete expressions are placed:
// example 1 int main(){ base* p = new derived; // ... delete p; return 0;}
// example 2 int main(){ derived d; // ... return 0;}
The usefulness of new and delete is that you can place them in different functions or destroy the object before the function has ended, and so on. As long as you store the pointer returned by new, you can pass it to delete to properly destroy the object.
In this situation, the pointer acts somewhat like a claim check at a repair shop. When you bring your item in to get repaired, the clerk gives you a claim check. You need that claim check to refer to the item by proving that you are the one who brought the item into the store. When the item has been repaired, you give the clerk the claim check, pay the bill, and he will give you back the repaired item.
The difference is that when you call "new" you get both a newly constructed object and the pointer and when you call delete you must give it back the pointer so that it knows which object to destroy.
base* p = new derived;delete p;
Take away the pointer, and how do you specify which object should be deleted? The object you created with "new derived" has no name:
new derived; // legal, but dumbdelete ; // huh?
Without a pointer you have no way of referring to the object...