Can we delete this pointer in a member function of class in C++ ?

 

Yes, we can delete “this” pointer inside a member function only if object has been created dynamically i.e. using “new” keyword. Because delete can be applied on the object that has been created using “new” keyword only. If member function  called using statically allocated object then a runtime crash will happen.


#include<iostream>
using namespace std;

//class that delete this pointer inside a member function.
class Test{

public:
  void function()
 { 
    delete this;
    cout<<"Deleted Object \n";
 } 
};

//Test function
int main()
{

    Test *pointer = new Test(); 
    pointer->function();// Ok

    Test object;
    object.function();// Run time crashing

    return 0;
}

No comments:

Post a Comment

My Kinect 3D Background and Foreground Subtraction Demo

Background subtraction is a classic computer vision technique used to separate the foreground (the subject of interest) from the backg...