In this article we will discuss what is exactly this pointer and what happens if we delete this pointer.

what is this pointer?

this pointer is a kind of pointer that can be accessed only inside non static member function and it points to the address of the object which has called the member function.

Whenever we call a member function through its object, compiler secretly passes the address of calling that object as first parameter in member function as this pointer .

So, we can access calling objects member variables inside member function

Suppose we have a class Dummy and it has a member variable m_value and a member function displayValue().

 

 

So, whenever we call the displayValue() member function from Dummy’s object, compiler secretly passes the address of Dummy’s object as first parameter to member function i.e

is secretly converted in to following by compiler,

also definition of displayValue is,

is secretly converted in to following by compiler,

So, when we accessed m_value, it uses the calling object to access the member value.

This is how this pointer works.

But,

what if we delete this pointer inside member function ?

Deleting this pointer inside member function is wrong, we should never do that. But if we do that following things can happen,

1.) If that object from which this member function is called is created on stack then deleting this pointer either crash your application or will result in undefined behaviour.

2.) If that object from which this member function is called is created on heap using new operator, then deleting this pointer will destroy the object. It will not crash the application at that particular time but after it if some member function will try to access the member variable through this object then application will crash.

Checkout this example,

Once we deleted the this pointer in destroy() member function, after this calling displayText() is safe because it is not accessing any member function. But calling displayValue() will crash the application because it is accessing member variable through a dangling pointer i.e. deleted this pointer.