Consider below code:
#include <iostream>
#include <string>
using namespace std;
class A{
public:
int x;
public:
A(){x=0;}
void fun1(){
cout << "fun1 is called \n";
cout << "Address of this is " << this <<endl;
delete this;
}
void fun2()
{
cout << "fun2 called \n";
}
~A()
{
cout << "Object Destroyed" << endl;
}
};
int main()
{
A* ptr=new A;
cout << "Address of ptr is " << ptr <<endl;
ptr->fun1();
ptr->fun2();
return(0);
}
The Output is:
$ ./TestCPP
Address of ptr is 0x20010318
fun1 is called
Address of this is 0x20010318
Object Destroyed
fun2 called
My question is that when we call delete
in fun1()
it destroys the object pointed by this
pointer i.e at address 0x20010318
. It calls the destructor as shown by output. Hence after calling fun1()
the object at address 0x20010318
is destroyed and that memory is freed. Then why in the output we can see fun2()
? Is it just the garbage value ? I mean the object does not exist but at location pointed by ptr -> fun2()
the definition of fun2()
still exists?
Also can someone please explain how delete
works. For instance calling new
calls operator new
and the constructor
, is delete
operation similar?
Thanks