Sams Teach Yourself C++ in 21 Days

(singke) #1
Understanding Object-Oriented Programming 169

6


On line 38, you make a local variable,Area, of type int. This variable holds the area of
the Rectanglethat you’ve created. You initialize Areawith the value returned by
Rectangle’s GetArea()function. A client of Rectanglecould create a Rectangleobject
and get its area without ever looking at the implementation of GetArea().
Rectangle.hppis shown in Listing 6.8. Just by looking at the header file, which contains
the declaration of the Rectangleclass, the programmer knows that GetArea()returns an
int. How GetArea()does its magic is not of concern to the user of class Rectangle. In
fact, the author of Rectanglecould change GetArea()without affecting the programs
that use the Rectangleclass as long as it still returned an integer.
Line 42 of Listing 6.9 might look a little strange, but if you think about what is happen-
ing, it should be clear. In this line of code, you are getting the x-coordinate from the
upper-left point of your rectangle. In this line of code, you are calling the
GetUpperLeft()method of your rectangle, which returns to you a Point. From this
Point, you want to get the x-coordinate. You saw that the accessor for an x-coordinate in
the Pointclass is GetX(). Line 42 simply puts the GetUpperLeft()and GetX()acces-
sors together:
MyRectangle.GetUpperLeft().GetX();
This gets the x-coordinate from the upper-left point coordinate that is accessed from the
MyRectangleobject.

FAQ
What is the difference between declaring and defining?
Answer: A declaration introduces a name of something but does not allocate memory. A
definition allocates memory.
With a few exceptions, all declarations are also definitions. The most important excep-
tions are the declaration of a global function (a prototype) and the declaration of a class
(usually in a header file).

Exploring Structures ............................................................................................


A very close cousin to the keyword classis the keyword struct, which is used to
declare a structure. In C++, a structis the same as a class, except that its members are
public by default. You can declare a structure exactly as you declare a class, and you can
give it the same data members and functions. In fact, if you follow the good program-
ming practice of always explicitly declaring the private and public sections of your class,
no difference will exist whatsoever.
Free download pdf