Can you delete this pointer inside a class member function in C++?

Answer: Yes, we can delete “this” pointer inside a member function only if the function call is made by the class object that has been created dynamically i.e. using “new” keyword. As, delete can only be applied on the object that has been created by using “new” keyword only.

If we call the function using statically allocated object then a runtime crash will happen.

Test Example:

#include<iostream>
using namespace std;

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

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

//Test function
int main()
{

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

	Test object;
	object.function();// Run time crash here

	return 0;
}

Notes: Same case is also applied to delete this pointer inside a class destructor in C++ program.

Related Posts