by John
Kopp
Introduction Welcome to About.com's
free tutorial on C++ programming. This lesson covers the
purpose and use of the "this" pointer. In addition to the
explicit parameters in their argument lists, every class
member function (method) receives an additional hidden
parameter, the "this" pointer. The "this" pointer addresses
the object on which the method was called. There are several
cases when the "this" pointer is absolutely required to
implement desired functionality within class methods.
Purpose To understand why the "this"
pointer is necessary and useful let's review how class members
and methods
are stored. Each object maintains its own set of data members,
but all objects of a class share a single set of methods. This
is, a single copy of each method exists within the machine
code that is the output of compilation and linking. A natural
question is then if only a single copy of each method exists,
and its used by multiple objects, how are the proper data
members accessed and updated. The compiler uses the "this"
pointer to internally reference the data members of a
particular object. Suppose, we have an Employee class that
contains a salary member and a setSalary method to update it.
Now, suppose that two Employees are instantiated.
class Employee
{ public: .... void
setSalary(double
sal) { salary
=
sal; } private: .... double
salary; .... }
int
main() { .... Employee
programmer; Employee
janitor;
janitor.setSalary(60000.0); programmer.setSalary(40000.0); .... }
| If only one setSalary method
exists within the binary that is running, how is the correct
Employee's salary updated? The compiler
uses the "this" pointer to correctly identify the object and
its members. During compilation, the compiler inserts code for
the "this" pointer into the function. The setSalary method
that actually runs is similar to the following
pseudo-code.
void setSalary(Employee *this, float
sal) { this->salary =
sal; } | The correct object is
identified via the "this" pointer. So what, you say.
Interesting, maybe. But if this implicit use of the "this"
pointer were all there was, this topic would mainly be of
interest to compiler designers. As we will see, explicit use
of the "this" pointer also has great utility.
Next
page > Concatenating
Calls > Page 1,
2,
3,
4
|