C++ this pointer
To understand ‘this’ pointer, it is necessary to know how objects look at functions and data members of a class.
- Each object gets its own copy of the data member.
- All-access the same function definition as present in the code segment.
This means each object of a class has a its own separate copies of data members but share the same member functions.
If there is only one copy of each member function and is used by multiple objects, how are the proper data members are accessed and updated?
The compiler provides an implicit pointer along with the names of the functions as ‘this’.
The ‘this’ pointer is passed as a hidden argument to all non-static member function calls and is available as a local variable within the body of all non-static functions.
a non-static method is one that is called ON an instance of some class, whereas a static method belongs to the class itself.
‘this’ pointer is not available in static member functions as static member functions can be called without any object
Every object in C++ has access to its own address through an important pointer called this pointer. The this pointer is an implicit parameter to all member functions. Therefore, inside a member function, this may be used to refer to the invoking object.
Friend functions do not have this pointer, because friends are not members of a class. Only member functions have this pointer.
Let us try understanding this concept with the help of an example