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