
CPP uses a unique keyword called 'this', to represent an object that invokes a member function. 'this' is a pointer type object that points to the same class for which it was called. 'this' is a unique pointer that is automatically passed to a member function when it is called. 'this' pointer acts as an implicit argument to all the member functions.
Example 1: this pointer refers to the class variable
#include<stdio.h>
#include<conio.h>
class example
{
int a, b;
public:
void input(int a, int b)
{
this->a = a; //instead of a=a
this->b = b; //instead of b=b
}
void output()
{
cout<<"A = "<<a<<"\nB = "<<b;
}
};
int main()
{
int a, b;
clrscr();
cout<<"Enter 1st number: ";
cin>>a;
cout<<"Enter 2nd number: ";
cin>>b;
example ex;
ex.input(a, b);
ex.output();
getch();
}
Example 2: this pointer refers to the class object. Input 2 numbers and find greater.
#include<stdio.h>
#include<conio.h>
class example
{
int a;
public:
void input(int x)
{
a = x;
}
example output(example ob)
{
if(a>ob.a)
return *this;
else
return ob;
}
void display()
{
cout<<"Value = "<<a;
}
};
int main()
{
int a;
clrscr();
cout<<"Enter 1st number: ";
cin>>a;
object1.input(a);
cout<<"Enter 2nd number: ";
cin>>a;
example object1, object2, object3;
object2.input(a);
object3 = object1.output(object2);
object3.display();
getch();
}
Ad: