C++ has a
keyword called this, which is used to represent the address of
object. An object can access its own address through this pointer.
When a member function is called, this pointer is
automatically passed to the member function. The this pointer is
implicit arguments to all member functions. But the this pointer is
not implicit argument to friend function, because friend function is not member
function.
Examples of this pointer in c++
#include<iostream>
using namespace std;
class Example
{
public:
int a, b;
public:
void setValue(int a, int b)
{
this->a = a;
this->b = b;
}
void swapping()
{
Example temp;
temp.a = this->a;
this->a = this->b;
this->b = temp.a;
}
void showValue()
{
cout<<"a =
"<<this->a<<"\nb = "<<this->b;
}
};
int main()
{
Example obj;
obj.setValue(5, 8);
obj.swapping();
obj.showValue();
return 0;
}
OUTPUT:
a = 8
b = 5
The this pointer can be used when both
local variable name and member arguments name are same.
Thanks For This Blog, Keep Sharing Your Thoughts Like This...
ReplyDeleteC++ Training in Chennai
Best C++ Online Course