Introduction
The Delete operator is used to deallocate Variable storage space. This pointer is a particular type of pointer that may only be accessed within non-static member functions and refers to the object's address that invoked the function. This pointer contains the address of the current object; in other words, this pointer points to the class's current object. In this article, we will learn about the delete this concept in detail. Let's dive into the article to get more information about this concept.
Also see, Literals in C.Fibonacci Series in C++
Delete This
When calling a member function through its object, the compiler covertly transmits the address of calling that object as the first parameter in the member function. This pointer should not, in general, be deleted with the delete operator.
Assume that if it is used, the following things must be considered. ‘this’ pointer should not, in most cases, be deleted with the delete operator.
- The delete operator is only applicable to objects created with the new operator. If new was used to create the object, we could remove it; otherwise, the action is unknown.
Program:
class temp {
public:
void func() {
delete this;
}
};
int main() {
/* Following is Valid */
temp *p = new temp;
p->func();
p = NULL;
/* And following is Invalid: Undefined Behavior */
temp x;
x.func();
getchar();
return 0;
}
Output:
free(): invalid pointer
- After this has been completed, no members of the removed object should be accessible.
Program:
#include<iostream>
using namespace std;
class temp {
int num;
public:
temp() { num = 0;}
void func() {
delete this;
/* Invalid: Undefined Behavior */
cout<<num;
}
};
int main()
{
temp* obj = new temp;
obj->func();
return 0;
}
Output:
0
Also Read - C++ Interview Questions