Write a C++ program to illustrate the use of this pointer.
In C++, this is a keyword which refers to the current object of the class. Most of the time this
keyword is used for following purposes:
- To refer the members of current class.
- To pass current object as parameter to another method.
Tutorial
Code
#include <iostream.h>
#include <conio.h>
class Number
{
int num;
public:
void set(int num)
{
this->num = num;
}
void displayNum()
{
cout << "\nNumber: " << num << endl;
}
};
void main()
{
clrscr();
Number n1; // n1 object of class Number
n1.set(10);
n1.displayNum();
getch();
}
Above example refers to scenario 1, as you can see within the setter function, the name of the method argument is same as the name of member variable in the class i.e. num. Thus, we are using this keyword to distinguish and in order to assign the parameter value to the current object’s member variable.
Comments