3
#include<stdio.h>

class test2
{
    public:

    void testFunc()
    {
        printf("test");
    }

    test2(){}
   ~test2(){}

};


class test1 : test2
{
    public:

    test1(){
        link = new test2();}    
    ~test1(){ 
        delete link;
        link = NULL;
    }


   test2* link = NULL;
    private:

};
 
 

int main()
{
  test1 *ptr = new test1();
  delete ptr;

  ptr->link->testFunc();


    return 0;
}

I want to delete the test2 object after calling the deconstructor of test1. Yet, Im still able, after calling delete and setting link to NULL, to call the member function "testFunc" and print "test" with the link pointer. Why is this possible?

Seonix
  • 33
  • 3
  • 1
    Because it’s undefined behavior – Taekahn Feb 06 '22 at 22:35
  • That's the nature of undefined behaviour. Too many people interpret that as meaning a program must crash, or somehow behave differently than it would without the presence of undefined behaviour. Whereas, in reality, any outcome is possible - including seeming to run as if the undefined behaviour is not there. Practically, it probably happens because nothing (not your program, not any function in the standard library, not the operating system, not some stray gamma ray) has caused the memory pointed to by your pointers to be overwritten before you use the pointers. – Peter Feb 07 '22 at 00:27
  • @OP Also, if the compiler can detect that the code makes no sense, the compiler is free to optimize away the nonsense code. For example, [this compiler](https://godbolt.org/z/avTfo8vYr) doesn't even generate the `delete ptr;` code. Another example of the compiler doing things like this is if you attempted to do something like `if (this == nullptr) { do_stuff; }` -- since `this` can never be `nullptr`, the compiler can remove that entire nonsense comparison. So be careful when trying to do this type of coding to test things. – PaulMcKenzie Feb 07 '22 at 00:55

1 Answers1

1

If a program accesses an object outside of its lifetime, then the behaviour of the program is undefined. Your program accesses an object outside of its lifetime. The behaviour of your program is undefined. The behaviour that you observed is because the behaviour is undefined. You could have observed any other behaviour because it is undefined, but you didn't observe other behaviour because it's undefined.

eerorika
  • 232,697
  • 12
  • 197
  • 326