0

While tracing the code given below. The code works fine on a single call to void Function(). It prints the respective values of x and y. But when I invoke the same function again, it throws me a runtime error. I see the usage of delete this in the function.

1. Does it mean that allocated stack of that function is freed?

2. What does delete this mean & Why the program throws runtime error?

#include<iostream> 
using namespace std;
class Point
{
    int x; 
    float y; 
    public:
    void Function()
    {
        x = 6; 
        y = 7.50; 
        delete this;
    }
    void Display()
    {
        cout<< x << " " << y;
    } 
}; 
int main()
{
    Point *ptr = new Point();
    ptr->Function();
    ptr->Function(); //Second call throws an error
    ptr->Display(); 
    return 0; 
}
Abhinav Kinagi
  • 3,653
  • 2
  • 27
  • 43
  • 1
    1. No, it means the memory belonging to the object has been not only freed but possibly reallocated for some other use, so its contents are unreliable. 2. It means, and it is because of, undefined behaviour. Don't do it. – user207421 Jul 27 '19 at 08:40
  • 1
    To understand this code you have to appreciate that your pointer is on the stack, but the object that is being pointed to is not. `delete this` deletes the object, it does nothing at all to the pointer. – john Jul 27 '19 at 08:43
  • 1
    *The allocated stack of that function*. This is very confused, stacks aren't allocated, they don't belong to functions. All that is happpening in the code is an object is being allocated, then freed, and then used after it has been freed. Which is an error. – john Jul 27 '19 at 08:45
  • I would guess that the idea was to free the memory used by the point object from within the class. You could move it to Display if the idea is to free each point after it is 'displayed'. – Paul McCarthy Jul 27 '19 at 09:38
  • @PaulMcCarthy No, you can't move it to anywhere inside any instance method of the class without entering in on UB. – user207421 Jul 27 '19 at 10:16

0 Answers0