1

I've written a very simple code. In created an object dynamically, and then I delete that object and assign it to zero. After that I access a member function of that object, but my program does not crash, instead it returns value.

class MyClass
{
public:
    MyClass() {}
    int funct() { return 0; }
};

int main()
{
    MyClass *mc = new MyClass;

    delete mc;
    mc = 0;

    // The program should crash here as I've set mc to zero after deleting 
    // it. But it returns the value.
    int retVal = mc->funct();

    return 0;
}

As per my understanding with new, delete and assignment to zero, this code should crash, or give exception.

njporwal
  • 111
  • 2
  • 4
  • 9

1 Answers1

7

You can visualize your method as a function:

int funct(MyClass *this) { return 0; }

You can see that the function doesn't use this at all so it won't crash if it is 0.

However, don't do such things in real code. This is still an Undefined Behavior and compiler optimizations can mess it up.

Piotr Siupa
  • 3,929
  • 2
  • 29
  • 65