Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

A Beginner Pointer Problem

Status
Not open for further replies.

HelloEarth

Programmer
Aug 26, 2004
3
0
0
US
//********************************
Telephone myPhone;
Telephone* myPhone2 = &myPhone;
delete myPhone2;
myPhone.blah();
//********************************

How can I use: myPhone.blah(); if the object is destroyed by the pointer? :(

What exactly is being deleted when I call:
"delete myPhone2"?
 
because you specify the same address too myPhone2
-- Telephone * myPhone2 = &myPhone;

when you delete myPhone you are also deleting myPhone2
because in essence they are the same thing.\

Alot of classes (all should but dont) come with a copy constructor. So you might be able to do this

Telephone * myPhone2 = new Telephone(myPhone);
delete myPhone; //nothing will happen to myPhone2
 
Oh no no I know it deletes myPhone2 because they are the same object. But what I ask is why does the method:
Code:
myPhone.blah();
work if the object is erased from memory?
 
Code:
delete myPhone; //nothing will happen to myPhone2
I can't do this because myPhone is not a pointer and my program will crash :(
 
You can't [tt]delete[/tt] something if it hasn't been allocated with [tt]new[/tt]...


> What exactly is being deleted?

Who knows? It's a wonder your program doesn't just crash. Using delete on a pointer pointing to memory not allocated with [tt]new[/tt] is illegal.

Now, if you allocated a chunk of memory with [tt]new[/tt], then you could have several pointers pointing to that memory. Using [tt]delete[/tt] on one of them would free the memory pointed to by all the pointers.


Even if you do (properly) delete memory containing an object, the memory is merely "marked" as free memory; the object is not "erased." Thus, you can still refer to that object through pointers. Doing so is bad and wrong and horrible, though.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top