What the computer does when an object calls a member function.
A member function is a function (method) specified in a class (or struct). Beginning C++ students work with free functions to start with. Free functions are not members of a class. This tutorial covers only member functions.
When an object calls a member function, the computer stores the address of the calling object in a temporary and invisible constant variable. A constant variable can not be changed. The name of this invisible constant variable is:
this
So this holds the address of the calling object. When multiple instances (objects) of a class exist, only the address of the method-calling object will be stored in this. The image below shows two instances of a class, NOT calling a member function:
If you ran one of the codes presented above, where the address of an object is displayed, then you know what those weird numbers mean in the blue boxes. The red coloured lines and box show that none of the objects' address can be passed to the this variable YET.
Next step:
An object calls a member function.
- Then the address of the calling object is stored in this.
- Then this is passed to the called member function internally.
- And that is the reason why a member function knows who the caller was!
The image below demonstrates obj_2 calling CSomeClass::Print():
That is all there is to tell about this. Our next step is to demonstrate the existence of this in simple code. However, realize that this is NOT the object itself. It is only the address of the calling object. *this is the actual object!