What is this pointer in c++?
Introduction
Member functions: operators and functions defined as members of a class.
Friend function: a function declared outside a class. However, it can access the class members’ protected and private data.
Non-static member function: a function defined in a member specification of a class without a static or friend specifier.
Each object in C++ can get its own address through an object called the this pointer. It is an implicit parameter to all member functions.
Therefore,
friendfunctions do not havethispointers as they are not class members.
this pointer in c++
The this pointer is passed as a hidden argument to all nonstatic member function calls. It is provided as a local variable inside every nonstatic function’s body.
The this pointer is useful in various scenarios as described in the code examples below:
Code
Example 1
In this example, the local variable and member have the same name. We declare a string named ‘e’. After this, we create a setter function for ‘e’. We pass the parameter in the function with the same name as the member. Here the this pointer differentiates between the member name and the local variable name. The this pointer gets the class object’s e and assigns it to the local variable. This implementation is shown in the main:
#include <iostream>#include "string.h"using namespace std;/* local variable name= member name */class Educative {private:string e;public:void sete (string e) {// The 'this' pointer// is used to get the class object's ethis->e = e;}void print() { cout << "e : " <<e << endl; }};int main() {string e = "Learn";Educative ed;ed.sete(e);ed.print();return 0;}
Example 2
When returning a reference to the calling object:
Educative& Educative::learn (){//Returns reference to the calling objectreturn *this;}