Extra 5% OFF Use Code: OL05
Free Shipping over ₹999

This Pointer

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 named name.
  • Inside this method, this->name refers to the class’s member variable, while name refers to the method’s parameter.
  • The this->name = name; line assigns the value of the parameter name to the member variable name.

Step 3: Create a Method to Display the Name

void display() {
    std::cout << "Name: " << this->name << std::endl;
}
  • The display method prints the name of the person.
  • this->name is used to access the member variable name 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 the Person class.
  • We set the name of person1 to “John” using the setName method.
  • We then call the display method to print out the name.

    Leave a Reply

    Your email address will not be published.

    Need Help?