As a simple example of
the class/object relationship, consider a point in an animated movie.
At one level, a point is two numbers (screen coordinates) that we treat
collectively as a single object. In mathematical notation, points are
often written in parentheses, with a comma separating the coordinates.
For example in WCM (0, 0) indicates the origin, and (x, y) indicates
the point x units to the right and y units down from the origin.
A natural way to represent a point in C++ is with two doubles, as will
be done here. (For WCM specifically, someone may think that integers
might be a better choice since there are no fractional pixels, but this
changes when using zoom). The question, then, is how to group these two
values into a compound object, or class
. The answer is a class definition:
Note that c
lass definitions appear outside of any function definition, usually at
the beginning of the program (after the include statements).
This definition indicates that there are two elements in this
. These elements are called instance variables, for reasons I will
explain a little later. The word
with a colon symbol at the end (
) means that the elements below are accessible for everybody. By
contrast, you cannot access an internal WCM object's ID or any other
parameter directly. This means that these parameters are not
. But we will discuss the protected data later.
t is a common error to leave off the semi-colon at the end of a class
definition. It might seem odd to put a semi-colon after a
squiggly-brace, but you’ll get used to it.
Once you have defined the new
class, you can create instances of type Point, called objects:
MyPoint.dX = 3.0;
MyPoint.dY = 4.0;
The first line is a conventional variable declaration:
MyPoint has type Point. The next two lines initialize the instance
variables of the class. The “dot notation” used here is similar to the
syntax for invoking a method on an internal WCM object, as in
Max.SetPos ( 0, 290 )
. One difference, however, is that function names are always followed by
an argument list, even if it is empty.
The result of these assignments is shown in the following state diagram
for the “MyPoint” object:
As usual, the name of the variable
appears outside the box and its value appears inside the box. In this
case, that value is a compound object with two named