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:

  1. #include <iostream>
  2. using namespace std;
  3. class example {
  4. private:
  5. int a;
  6. char b;
  7. public:
  8. void set(int a, char b) {
  9. this->a=a;
  10. this->b=b;
  11. }
  12. voiddisplay() {
  13. cout << a << endl;
  14. cout << b;
  15. }
  16. };
  17. int main() {
  18. example obj;
  19. obj.set(1000, 'b');
  20. obj.display();
  21. return 0;
  22. }


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:

  1. #include <iostream>
  2. using namespace std;
  3. class example {
  4. private:
  5. int a;
  6. char b;
  7. public:
  8. example &set(int a) {
  9. this->a=a;
  10. return *this;
  11. }
  12. example &setCh(char b) {
  13. this->a++;
  14. this->b =b;
  15. return *this;
  16. }
  17. voiddisplay() {
  18. cout << a << endl;
  19. cout << b;
  20. }
  21. };
  22. int main() {
  23. example obj;
  24. //Chaining calls
  25. obj.set(1000).setCh('b');
  26. obj.display();
  27. return 0;
  28. }


Limitation of this pointer

  1. this pointer cannot have used into static data member function. Because, for calling static data member do not need any object.
  2. this pointer cannot used into friend function, because friend function is not member of a class. Only member functions have this pointer.