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; } |
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++:
- Resolve Shadowing Issue Using this Keyword.
- Access Currently Executing Object Using this Keyword.
- Access Data Members Using this Keyword.
- Calling Member Functions Using this Keyword.
Let’s start discussing these different ways in detail.