In: Computer Science
This represents a POINTER in C++
Every object in C++ have access to its own address through an important pointer called as this pointer
in C++ this pointer is used to hold the address of an object inside a member function
for example;
let say there is an object called obj which is calling its own member function method() as obj.method() then this pointer will hold the address of object obj inside the member function method()
ultimately we can say that it will point to the object for which this function is called.
it is automatically passed to the member function when it is called i.e when you call obj.method() this will set to address of obj
for eample:
the following progrm:
#include<iostream.h>
#include<conio.h>
class UseThisPointer{
int b;
public: void setData(int b){
this->b = b; //this will separate the member data with
argument
}
void printData()
{
cout<<"The value of b is"<<b<<endl;
}
};
int main(){
clrscr();
UseThisPointer tp;
tp.setData(10);
tp.printData();
getch();
return 0;
}
will produce the output:
the value of b is 10
b is a private data member of class UseThisPointer since argument of method setData is also b without using this explicitly both will be taken as data members
Use of this in C++
Return Object
one of the most important use of this pointer in C++ is to return object this points to
for example
the statement
*this
inside a member function will return the object which calls the fuction