C++

“This” Pointer In C++ – Detailed Question And Answer

In plain English, you may say that the this pointer points to the current object of the class because it contains the address of the current object. Let’s use an illustration to help you grasp this idea.

C++ Example: this pointer

You can see that there are two data members—num and ch—in this instance. There are two local variables with the same names as the data members in the member method setMyValues(). In this situation, you won’t be able to assign the local variable value to the object’s data members without using this pointer since the compiler won’t recognize that you are referring to the object’s data members without it. This is one of the instances where this pointer must be used.

#include <iostream>
using namespace std;
class Demo {
private:
  int num;
  char ch;
public:
  void setMyValues(int num, char ch){
    this->num =num;
    this->ch=ch;
  }
  void displayMyValues(){
    cout<<num<<endl;
    cout<<ch;
  }
};
int main(){
  Demo obj;
  obj.setMyValues(100, 'A');
  obj.displayMyValues();
  return 0;
}

Output:

100
A

Example 2: Using this reference to chain calls between functions

In order to chain function calls and call all of the functions for the current object at once, another example of how to use this pointer is to return the reference of the current object. Another crucial aspect of this program to keep in mind is that I increased the object’s num value in the second function, and the output shows that this actually increased the value that was set in the first function call. This demonstrates that the chaining is sequential and that any modifications made to the data members of the object 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;
  }
  Demo &setCh(char ch){
    this->num++;
    this->ch =ch;
    return *this;
  }
  void displayMyValues(){
    cout<<num<<endl;
    cout<<ch;
  }
};
int main(){
  Demo obj;
  //Chaining calls
  obj.setNum(100).setCh('A');
  obj.displayMyValues();
  return 0;
}

Output:

101
A

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button