Sunil Sharma
Sunil Sharma

Reputation: 163

Behavior of delete this pointer in C++

I am trying to explore this pointer in c++ . I have created a pointer to class object and caling a function to delete the current object but the behavior is unexpected.

Why output of the last print statement is x= 0 , y= 6.

#include<iostream>
using namespace std;

class Test
{
private:
  int x;
  int y;
public:
  Test(int x = 6, int y = 6) { this->x = x; this->y = y; }
  void setX(int a) { x = a; }
  void setY(int b) { y = b; }
  void destroy()  { delete this; 
 }
  void print() { cout << "x = " << x << " y = " << y << endl; }
};

int main()
{ 
  Test *obj = new Test();
  Test objs;
  obj->print();
  obj->destroy();

  obj->print();
  return 0;
}

Upvotes: 0

Views: 602

Answers (1)

P0W
P0W

Reputation: 47814

Deleting this is legal , which calls the destructor of class

However, if the object was not allocated using new, it will be a Undefined Behavior

But you have to be absolutely sure that this will be last member function invoked on this object and none of of your member function (after the delete this line) gets called through this object, since this will become a dangling pointer, which should not be dereferenced.

If you do these, the behavior will be undefined, so can see anything in your output.

Upvotes: 3

Related Questions