I just wrote a sample program to see the behaviour of delete this
class A
{
~A() {cout << "In destructor \n ";}
public:
int a;
A() {cout << "In constructor \n ";}
void fun()
{
cout << "In fun \n";
delete this;
cout << this->a << "\n"; // output is 0
this->fun_2(); // how m able to call fun_2, if delete this is called first ??
}
void fun_2()
{
cout << "In fun_2 \n";
}
main()
{
A *ptr = new A;
ptr->a = 100;
ptr->fun(); //delete this will be executed here
ptr->fun_2(); //how m able to execute fun_2 when this pointer is deleted ??
cout<< ptr->a << "\n"; //prints 0
return 0;
}
> Output
In constructor
In fun
In destructor
0
In fun 2
In fun 2
0
Questions
m using linux ubuntu and g++ compiler
Eric Lippert provided a very nice "book in a table drawer of a hotel room" analogy in his answer to a question about pointers to local variables after the function has returned, it is equally applicable here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With