In this post, we are going to learn about the use of this keyword and how to apply it?
“this” is a keyword in C++ programming that refers to the current instance of the class. In C++, the “this” keyword can be used in three different ways.
- this can be used to pass current object as a parameter to another method.
Let’s how to pass a current object as a parameter to another method through an example:
#include<iostream> using namespace std; class Demo { public: int x=23; void m1() { cout<<"m1 calling."<<endl; m2(this); } void m2(Demo *d) { cout<<d->x; } }; int main() { Demo d1; d1.m1(); return 0; }
Output:
m1 calling.
23
- this can be used to refer current class instance variable.
- this can be used to declare indexers.
C++ this Pointer Example:
Distinguish Data Members:
Let’s take a look at an example of this keyword in C++ that refers to the current class’s fields:
#include <iostream> using namespace std; class Employee { public: int id; //data member (also instance variable) string name; //data member(also instance variable) float salary; Employee(int id, string name, float salary) { this->id = id; this->name = name; this->salary = salary; } void display() { cout<<id<<" "<<name<<" "<<salary<<endl; } }; int main(void) { Employee e1 = Employee(101, "Lingaraj", 900000); //creating an object of Employee Employee e2 = Employee(102, "Senapati", 89000); //creating an object of Employee e1.display(); e2.display(); return 0; }
Output:
101 Lingaraj 900000
102 Senapati 89000
Function Chaining Calls Using this pointer:
Another example of how to use this pointer is to return the current object’s reference so that you may chain function calls and call all of the current object’s functions at once.
Another thing to note in this programme is that in the second function, I increased the value of the object’s num, and you can see in the output that it truly incremented the number that we set in the first function call.
This demonstrates that the chaining is sequential and that the modifications made to the object’s data members are preserved for subsequent chaining calls.
#include <iostream> using namespace std; class Demo { private: int num; char ch; public: Demo &setNum(int num){ this->num =num; return *this; //return objects } Demo &setCh(char ch){ this->num++; this->ch =ch; return *this; //return objects } void displayMyValues(){ cout<<num<<endl; cout<<ch; } }; int main() { Demo obj; //Chaining calls obj.setNum(100).setCh('B'); obj.displayMyValues(); return 0; }
Output:
10
B
Return Object:
One of the important applications of using this pointer is to return the object it points to.
Example: return *this;