Sometimes in C++ we need to access the address of an object and that time use this pointer.
#include <iostream>
using namespace std;
class Keyword{ // A class is Declared
public:
Keyword(int a, int b) //Regular Constructor initialized with two parameters
:x(a),y(b)
{
}
void printOut(){
sum = x+y;
cout<<"The sum is(using keyword): "<<this->sum<<endl; //sum output using this keyword
cout<<"The sum is:(regular output) "<<sum<<endl; //regular output
cout<<"The sum is(using this as pointer): "<<(*this).sum<<endl; //sum output using this as a pointer
}
private: //Three integer variables are initialised under as private members
int x;
int y;
int sum;
};
int main() {
Keyword NewOb(10,26); //NewOb object is created under Keyword class and it passes two values to the parameter of the constructor
NewOb.printOut(); //printOut function is called here to display the three different ways to output the same thing using this keyword
}
/*
* Output:
*The sum is (using keyword): 36
The sum is(regular output): 36
The sum is (using this as pointer): 36
*/
· This keyword is only to be used inside a member function.
· It refers to the object when it will be called by the main function.
· Here as we can see that we output the same thing with three different ways.
· As this is used as a pointer to the object, thus arrow selection operator is used to select the member variable.
· This keyword has its own importance and it is also used in operator overloading.