When you are writing code in a member function, the predefined variable this
contains a pointer to the current object. Any member element, for example m_x
, can be referenced
in two ways:
m_x = 10; this->m_x = 10; // same as above.
References to members are usually written without this
because there is no need to use it, however, there are situations where
this
is needed.
If a naming convention isn't used that makes member/instance variables
clear (eg, prefixing such variables with "m_"), the use of this
can be used to document the nature of the variable. Naming rules are to be
preferred however.
The primary use of this
is to return a pointer
to the current object, or to pass the object to a function.