C++ this Pointer
this keyword is a pointer. this pointer holds an address of current class objects.
In the below example, this pointer differentiates between the data member (int a, char b) and local variables into declared member function, void set (int a, char b). If, this pointer not distinguish or differentiates there we seen “compile time error” or “garbage value “into output screen.
Example:
#include <iostream>
using namespace std;
class example {
private:
int a;
char b;
public:
void set(int a, char b) {
this->a=a;
this->b=b;
}
voiddisplay() {
cout << a << endl;
cout << b;
}
};
int main() {
example obj;
obj.set(1000, 'b');
obj.display();
return 0;
}
Example of chaining call:
Here, mainly chaining call of a function happened. Into, main function section using example class object obj called two function combining with getting the help of this pointer.
Example:
#include <iostream>
using namespace std;
class example {
private:
int a;
char b;
public:
example &set(int a) {
this->a=a;
return *this;
}
example &setCh(char b) {
this->a++;
this->b =b;
return *this;
}
voiddisplay() {
cout << a << endl;
cout << b;
}
};
int main() {
example obj;
//Chaining calls
obj.set(1000).setCh('b');
obj.display();
return 0;
}
Limitation of this pointer
- this pointer cannot have used into static data member function. Because, for calling static data member do not need any object.
- this pointer cannot used into friend function, because friend function is not member of a class. Only member functions have this pointer.