Pixel
. The subroutine
pixelReset
resets the coordinate of a pixel. In other words,
it sort of belongs to the Pixel
class. In C, there is no way
to associate the subroutine pixelReset
with a struct
called Pixel
.
However, in C++, we can actually associate a subroutine with the definition of a class. In this case, we can redefine our class as follows:
class Pixel { public: int x, y; // coordinate void reset(void); };
The extra line states that there is a member function
reset
associated with the class Pixel
. Next, we can
define the member function:
void Pixel::reset(void) { x = 0; y = 0; }
Where is the parameter? How do we know whose x
and y
are
getting reset? Good questions, indeed!
Let us example how a variable of the class Pixel
can be used.
Pixel dotA; dotA.reset(); // reset dotA to the origin
We are calling the method reset
of object dotA
. Consequently,
the x
and y
of subroutine reset
refers to
those of dotA
.
In other words, all data and function members of a class are, by default, available to the definition of a function member. Furthermore, each data member reference in a member function refers to the data member of the object associated with the invocation.
This means that in dotB.reset()
, the member subroutine reset
accesses the data members x
and y
of dotB
.
One advantage of this approach is that there is no need to use the dot notation to access data members inside the definition of a member function. This encourages a programmer to think more in object oriented terms.
At this point, the availability of member functions is merely a syntactic change compared to our usual ways of defining subroutines to handle a particular type. However, as we will see later in this module, as well as other modules depending on this module, member functions is a very important feature of C++.
Copyright © 2006-09-26 by Tak Auyeung