As mentioned earlier,
C++ is generally considered an object-oriented
programming (OOP) language
. One of the features of OOP is that it provides a way to define objects
that behave very much like real world objects. For example, the class
Point we defined before, obviously corresponds to the way people think
about coordinates on the screen or in the movie, and the operations we
) correspond to the sorts of things people do with these coordinates.
So far, though, we have not taken advantage of the features C++ provides
to support object-oriented programming (except using internal WCM
objects). Strictly speaking, these features are not necessary. For the
most part they provide an alternate syntax for doing things we have
already done, but in many cases the alternate syntax is more concise
and more accurately conveys the structure of the program.
For example, at first glance there is no obvious connection between
. With some examination, it is apparent that these functions take at
least one point object as an argument.
This observation is the motivation for member
or so called methods
. Member functions differ from the other functions we have written in
When we call the function, we invoke it on an object, rather than just
it. People sometimes describe this process as “performing an operation
on an object,” or “sending a message to an object.”
The function is declared inside the
definition, in order to make the relationship between the structure and
the function explicit.
Note: It was mentioned earlier that the names “function” and “method”
are used differently in different languages and, in informal
discussions, are essentially the same. “Method” and “Member Function”
as used in this section have very specific C++ definitions.
In the next few sections, we will take
some functions and transform them into member functions or C++ methods.
One thing you should realize is that this transformation is purely
mechanical; in other words, you can do it just by following a sequence
Anything that can be done with a member function can also be done
with a nonmember function (sometimes called a free-standing function).
But sometimes there is an advantage to one over the other. If you are
comfortable converting from one form to another, you will be able to
choose the best form for whatever you are doing.