Sams Teach Yourself C++ in 21 Days

(singke) #1

168 Day 6


Some compilers report an error if you declare a class named Rectangle. This
is usually because of the existence of an internal class named Rectangle. If
you have this problem, simply rename your class to myRectangle.

NOTE

Within the declaration of the class Point, you declare two member variables (itsXand
itsY) on lines 12 and 13. These variables hold the values of the coordinates. As the x-
coordinate increases, you move to the right on the graph. As the y-coordinate increases,
you move upward on the graph. Other graphs use different systems. Some windowing
programs, for example, increase the y-coordinate as you move down in the window.
The Pointclass uses inline accessor functions declared on lines 7–10 to get and set the x
and y points. The Pointsclass uses the default constructor and destructor. Therefore, you
must set their coordinates explicitly.
Line 17 begins the declaration of a Rectangleclass. A Rectangleconsists of four points
that represent the corners of the Rectangle.
The constructor for the Rectangle(line 20) takes four integers, known as top,left,
bottom, and right. The four parameters to the constructor are copied into four member
variables (Listing 6.9), and then the four Pointsare established.
In addition to the usual accessor functions,Rectanglehas a function GetArea()declared
on line 43. Instead of storing the area as a variable, the GetArea()function computes the
area on lines 28 and 29 of Listing 6.9. To do this, it computes the width and the height of
the rectangle, and then it multiplies these two values.
Getting the x-coordinate of the upper-left corner of the rectangle requires that you access
the UpperLeftpoint and ask that point for its x value. Because GetUpperLeft()is a
method of Rectangle, it can directly access the private data of Rectangle, including
itsUpperLeft. Because itsUpperLeftis a Pointand Point’s itsXvalue is private,
GetUpperLeft()cannot directly access this data. Rather, it must use the public accessor
function GetX()to obtain that value.
Line 33 of Listing 6.9 is the beginning of the body of the actual program. Until line 36,
no memory has been allocated, and nothing has really happened. The only thing you’ve
done is tell the compiler how to make a point and how to make a rectangle, in case one is
ever needed.
On line 36, you define a Rectangleby passing in values for top,left,bottom, and
right.
Free download pdf