<hs******@gmail .comwrote in message
news:11******** **************@ i42g2000cwa.goo glegroups.com.. .
Consider the below code snippet:
#include <iostream>
using namespace::std;
class myclass
{
public:
myclass() {
cout << "constructo r" << endl;
}
~myclass() {
cout << "destructor " << endl;
}
void func() {
cout << "func" << endl;
}
};
int main(void) {
myclass *obj = new myclass();
delete obj;
obj = NULL; // obj = (myclass*)0;
obj->func(); //..............m ust be a crash..... but works fine
return 0;
}
i tried the above code in Microsoft compiler 12.0, 13.0 and g++.
the code doesnt crash and the output will be like
constructor
destructor
func
i really dont know how when obj is null, obj->func() is valid and not
crashing ?????????????/
anybody has an idea about it ??????????
Yes. It's just the implementation. Lets take a look at your calls one by
one.
myclass* obj = new myclass();
This makes obj a pointer to myclass and allocates the memory for it, which
runs the constructor.
delete obj;
This runs the destructor for MyClass and releases the memory.
obj = NULL;
This makes the obj point to nothing.
obj->func();
Okay, so what happens here? The compiler will call the function func()
(which there is only one copy of for no matter how many instances of
MyClass), which gets passed the address of obj (NULL in this case) as the
this pointer.
func() is run, and simply consists of a cout statement, which works.
If you have your func() attempt to output a variable located in MyClass,
however you will get a memory read error (sig fault on linux, memory
exception reading location 0x0000XXXX in windows).
If you do not set
obj = NULL;
it may appear to work sometimes because the memory hasn't been allocated and
changed by another object yet, but othertimes it may give you bad output or
other errors (depending on if another object has allocated the memory and
changed it, or perhaps the page the memory is on has been swapped out
because no object is using that memory, etc..).
Notice, I am only explaining *why* it did not crash for you. I am not
saying you should do this. This is a Bad Idea. But I find that
understanding what is going on beneight the covers sometimes helps me
understand code better.