How to remove a class object?

There is a class:
class point
{
public: 
 int x, y;

 point(int x, int y)
{
 this -> x = x;
 this -> y = y;
}

 void show()
{
 printf("(%d, %d)", x, y);
}

 void kill()
{
 delete this;
}

~point()
{
printf("destruct");
}
};


I put inside the function kill, which has to delete the object class, invoking it through this.
point a(5, 7);
a.kill(); //delete the object received in the console "destruct"
a.show(); //values (5, 7) are displayed in the console

It works and prints to the console "destruct". But then the object does not disappear. To it is still possible to handle and display the values xy. This program completes, the console displays "destruct" for the second time. That is, the object really somewhere hangs and then deleted again. Why is this happening and how to destroy the object?
March 19th 20 at 08:33
1 answer
March 19th 20 at 08:35
Solution
It works and prints to the console "destruct". But then the object does not disappear.

You have to learn a lot. That is undefined behavior. That delete with operator delete only objects created by new operator. That refer to fields of the object after the destructor is called -- this is undefined behavior as the destructor is called more than once. That is up to the programmer -- to follow the rules of the language, and the runtime can ignore the error, and can be quite vocal and complete the program at the first opportunity.

It works and prints to the console "destruct". But then the object does not disappear. To it is still possible to handle and display the values xy. This program completes, the console displays "destruct" for the second time.

Well, I have expected your program crashes immediately at the place of calling delete.

how to destroy object?

The object on the stack can be properly destroyed in two ways: natural -- coming out of the block in which it is defined and enforced -- by calling its destructor explicitly and creating in its place another object.
So how to explicitly call the destructor? - thora_Herman commented on March 19th 20 at 08:38
how to explicitly call the destructor?

@thora_Herman, a.~point(); - Eleazar.We commented on March 19th 20 at 08:41
I removed the delete caused distructor explicitly, but the output in the console is the same. The object is removed again 2 times and again outputs the data of XY after the first removal. Why? My goal is to free up memory. - thora_Herman commented on March 19th 20 at 08:44
the output in the console still

@thora_Herman, as it should be, because by and large nothing has changed. You have to learn a lot. That there is a difference between destruction of the internal state of an object and deallocation of memory.

My goal is to free up memory.

Memory object allocated on the stack can be released only after leaving the function in which it is created. There is no other way. - Eleazar.We commented on March 19th 20 at 08:47

Find more questions by tags C++