this pointer

Let us understand with an example how and where this pointer is used.

class employee {
unsigned int m_age;
unsigned int m_salary;
employee(unsigned int age, unsigned int salary) {
m_age = age; // same as this->m_age = age;
m_salary = salary; //same as this->m_salary = salary

}

void update(unsigned int age, unsigned int salary) {
m_age = age; // same as this->m_age = age;
m_salary = salary; //same as this->m_salary = salary
}
};
int main() {
employee emp(40, 45000);
emp.update(40, 50000);
return 0;
}

In the above example, employee object viz. emp is created.
When function viz. update is called using emp object, emp object is implicitly passed in the update function.
emp.update (40, 50000);
converted internally to:
emp.update(&emp, 40, 50000);

Similarly,
void update(unsigned int age, unsigned int salary);
converted internally to:
void update(employee* const this, unsigned int age, unsigned int salary);

  • this pointer is passed as an hidden argument to all the nonstatic member function. This functionality helps in accessing the data member of an object in nonstatic member functions.

  • Friend functions do not have this pointer since they are not members of a class.

  • Static functions do not have this pointer.

  • this pointer is not a member of a class nor it is stored anywhere.

  • this pointer can be used in the constructor as well because when we create an object, memory is allocated by compiler and address of that memory location is passed as a hidden parameter to the constructor which is nothing but a this pointer as shown in the above example


Related posts