Access Data Members Using this Keyword

Below is the C++ program to use this keyword to access the data member of the currently executing object:

C++




// Below is the C++ program to use
// this keyword to access the data 
// members of currently executing 
// object
#include <iostream>
using namespace std;
  
class GFG 
{
  string name;
    
  public:
  GFG(string name)
  {
    // Initialize value of class member 
    // name as the parameter name passed 
    // in the constructor.
    this->name = name;
  }
    
  void display()
  {
    // Accesses string data member name
    cout << this->name << endl;
  }
};
  
// Driver code
int main()
{
  GFG gfg("w3wiki");
  gfg.display();
  return 0;
}


Output

w3wiki

C++ Program to Show Use of This Keyword in Class

Here, we will see how to use this keyword in a class using a C++ program. this keyword in C++ is an implicit pointer that points to the object of the class of which the member function is called. Every object has its own this pointer. Every object can reference itself by this pointer. 

There are 4 ways this keyword can be used in a class in C++:

  1. Resolve Shadowing Issue Using this Keyword.
  2. Access Currently Executing Object Using this Keyword.
  3. Access Data Members Using this Keyword.
  4. Calling Member Functions Using this Keyword.

Let’s start discussing these different ways in detail.

Similar Reads

1. Resolve Shadowing Issue Using this Keyword

Shadowing occurs when there is a local variable that has the same name as an instance variable. Below is the C++ program to show how this keyword can be used to resolve the shadowing issues:...

2. Access Currently Executing Object Using this Keyword

...

3. Access Data Members Using this Keyword

This keyword can be used to chain functions and delete objects via its member functions....

4. Calling Member Functions Using this Keyword

...