Pointer still able to call member function, after it was set to NULL and delete being called on it

Viewed 64
#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?

1 Answers

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.

Related