In this guide we will learn the concept of 'this' pointer, it's use and how to implement in the C++ program.
When we create an object, we can access its address through an important pointer called this pointer. The 'this' pointer is used as an implicit parameter to all the member functions.
We pass the 'this' pointer as a hidden argument to all nonstatic member function calls which is available as a local variable within the body of functions.
1. Suppose there is an object xyz calling one of the member functions say sample().
2. Then the function sample() will hold the address of object xyz through this pointer.
3. The this pointer acts as an implicit argument to all member functions here.
There are many ways to use this pointer:
When the variable declared inside the class is same as the variable used in the method to accept the parameter/argument, we use this pointer to distinguish between the two when assigning values.
Example
class abc{ int p,q; public: abc(int p,int q) { this->p=p; //Here the variable used with this is class variable } };
We use this pointer to return the reference to the object it points to.
Example
class abc{ int p,q; public: abc& functionName() { //Statements return *this; //returns the reference to the object } };
#include using namespace std; class student{ private: int rollno,marks; public: student(int rollno=2) { this->rollno=rollno; } student& getstudent(int n) { cout<<"\nThe value of private variable declared in class= "<<rollno; //parameter assigned to class variable in above method cout<<"\nThe address of object= "<<this; marks=n; return *this; //returns current object } void showstudent() { cout<<"\nThe address of object= "<<this; cout<<"\nThe marks= "<<marks; } }; int main() { student st; st.getstudent(98).showstudent(); //No need to call showstudent() explicitly,we call it on the returned object return 0; }
Submitted by Akansh Upadhyay (akansh)
Download packets of source code on Coders Packet
Comments