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

Rendering 3D maps on the web using opesource javascript library Cesium

This is a simple 3D viewer using the Cesium javascript library. The example code can be found here . Click on question-mark symbol on upp...