Pointers are always headache for Programmers. However C++ have a special pointer which is referred as 'this'. The this pointer is one of the important concept in C++ and can be really confusing too. So in this article I will be discussing about the this pointer and its role in C++.
The this Pointer
Let us see an example first.
#include<iostream>
using namespace std;
class A{
int a;
public:
//constructor
A(int x = 0):a(x){}
void display() const{
cout<<a<<'\n';
}
};
int main(){
A objA(10);
A objB(11);
objA.display();
objB.display();
return 0;
}
It is very clear that the output will be
10
11
The program looks very simple, But do you know whats going on, under the Hood?
How does the function remember, which object is invoking it?
This is where the this pointer comes in action. Actually, the Compiler is secretly passing a constant pointer pointing to the object which invokes the function.
That is, even if you pass no parameter to the function a pointer pointing to the calling object is being passed as an argument.
To verify the above statement let us change our function declaration to
void display() const{
cout<<this->a<<'\n';
}
and recompile and run the program again. It is no surprise that the output is:
10
11
We used -> operator because this is a pointer and we cannot use the .(dot operator) with pointers.
However, it should be noted that this is not a ordinary variable, we cannot take the address or assign a value to this.
Remember That!
Friend and Static member function don't have access to the this pointer.
Consequences of this
In one of my previous article I talked about Operator Overloading in C++ where if the overloaded operator is a member function the number of parameters reduces by one, it is all due to this pointer.
To know more about the behaviour of the this pointer in operator overloading, You can refer to my another article here.
That's It
Happy Coding!
Comments
Post a Comment