Index
Definition
The this
pointer is an implicit pointer available in every non-static member function of a class. It points to the object for which the member function is called.
Purpose: It allows you to refer to the calling object inside the class’s member functions. This is especially useful when the parameters or local variables of a function have the same name as the class’s member variables.
Simple Example
Let’s create a simple class called Person
that has a name
attribute. We’ll also have a function to set the name of the person using the this
pointer.
Code
#include <iostream>
#include <string>
using namespace std;
class Person {
private:
string name;
public:
// Method to set the name
void setName(string name) {
// Using the 'this' pointer to refer to the object's name
this->name = name;
}
// Method to display the name
void display() {
cout << "Name: " << this->name << endl;
}
};
int main() {
// Create a Person object
Person person1;
// Set the name using the setName method
person1.setName("John");
// Display the name
person1.display();
return 0;
}
Output:
Name: John
Explanation
Step 1: Define a Class with a Private Member
class Person {
private:
std::string name; // Private member variable
};
Here, we have a Person
class with a private member variable name
. This variable will store the name of the person.
Step 2: Create a Setter Method with a Parameter Name Conflict
void setName(std::string name) {
this->name = name;
}
- The
setName
method takes a parameter namedname
. - Inside this method,
this->name
refers to the class’s member variable, whilename
refers to the method’s parameter. - The
this->name = name;
line assigns the value of the parametername
to the member variablename
.
Step 3: Create a Method to Display the Name
void display() {
std::cout << "Name: " << this->name << std::endl;
}
- The
display
method prints thename
of the person. this->name
is used to access the member variablename
of the object that called the method.
Step 4: Use the Class in the main
Function
int main() {
Person person1; // Create an object of the Person class
person1.setName("John"); // Set the name using the setName method
person1.display(); // Display the name
return 0;
}
- We create an object
person1
of thePerson
class. - We set the name of
person1
to “John” using thesetName
method. - We then call the
display
method to print out the name.