Sams Teach Yourself C++ in 21 Days

(singke) #1
Understanding Object-Oriented Programming 165

6


This technique enables you to put your declarations into a different file from your imple-
mentation, yet have that declaration available when the compiler needs it. This is a very
common technique in C++ programming. Typically, class declarations are in an .hppfile
that is then #included into the associated .cppfile.
Lines 18–29 repeat the mainfunction from Listing 6.4. This shows that making these
functions inline doesn’t change their performance.

Classes with Other Classes as Member Data ......................................................


It is not uncommon to build up a complex class by declaring simpler classes and includ-
ing them in the declaration of the more complicated class. For example, you might
declare a wheel class, a motor class, a transmission class, and so forth, and then combine
them into a car class. This declares a has-a relationship. A car has a motor, it has wheels,
and it has a transmission.
Consider a second example. A rectangle is composed of lines. A line is defined by two
points. A point is defined by an x-coordinate and a y-coordinate. Listing 6.8 shows a
complete declaration of a Rectangleclass, as might appear in Rectangle.hpp. Because
a rectangle is defined as four lines connecting four points, and each point refers to a
coordinate on a graph, you first declare a Pointclass to hold the x- and y-coordinates of
each point. Listing 6.9 provides the implementation for both classes.

LISTING6.8 Declaring a Complete Class


1: // Begin Rectangle.hpp
2: #include <iostream>
3: class Point // holds x,y coordinates
4: {
5: // no constructor, use default
6: public:
7: void SetX(int x) { itsX = x; }
8: void SetY(int y) { itsY = y; }
9: int GetX()const { return itsX;}
10: int GetY()const { return itsY;}
11: private:
12: int itsX;
13: int itsY;
14: }; // end of Point class declaration
15:
16:
17: class Rectangle
18: {
19: public:
20: Rectangle (int top, int left, int bottom, int right);
Free download pdf