this Pointer

Estimated reading: 3 minutes 18 Views

In object-oriented programming (OOP) languages like C++, the this pointer is a keyword that is used to refer to the current object within a member function. It is a special pointer that holds the memory address of the current object instance.

Example 1:

#include <iostream>
using namespace std;
class stud {
    public:
        void address() {
            cout << this;
        }
};
int main()
{
    stud a, b, c;
    cout << "The adress of a\t";
    a.address();
    cout << endl << "The adress of b\t";
    b.address();
    cout << endl << "The adress of c\t";
    c.address();
    cout << endl;
    return 0;
}

In this C++ code, we have a class named stud, which contains a member function address(). This member function simply prints the memory address of the current object using the this pointer.

Function of this Pointer:

  • In the address() function of the stud class, this refers to the current object for which the member function is being called.
  • Inside the address() function, cout << this; prints the memory address of the current object.
  • In the main() function, we create three objects a, b, and c of the class stud.
  • We then call the address() function on each object, which prints the memory address of each object.
  • The this pointer ensures that the correct memory address of the current object is printed when address() function is called for each object.

Example 2:

#include <iostream>
using namespace std;
class Student {
        int id;
    public:
        void set_id(int id) {
            this->id = id;
        }
        void print_id() {
            cout << "ID is " << id << endl;
        }
};
int main()
{
    Student St;
    St.set_id(10);
    St.print_id();
    return 0;
}

In this C++ code, we have a class named Student with a private member variable id representing the student’s ID. The class provides two member functions: set_id() and print_id().

Function of this Pointer:

  • In the set_id() member function, the parameter id passed to the function has the same name as the member variable id of the class. To distinguish between them, the this pointer is used.
  • Inside the set_id() function, this->id = id; assigns the value of the parameter id to the member variable id of the current object.
  • The this pointer points to the current object for which the member function is called. It is used to access members of the object.
  • In the main() function, an object St of the class Student is created. The set_id() function is called to set the ID of the St object to 10.
  • Then, the print_id() function is called to print the ID of the St object.

The output of the code will be:

ID is 10

 

Share this

this Pointer

Or copy link

CONTENTS
English