Sams Teach Yourself C in 21 Days

(singke) #1

Using Classes as Data Members ........................................................................


When you learned about structures and looping constructs in C, you also learned about
nesting. You learned that nesting was simply placing one statement or block inside of
another. Like everything else you learned in C, nesting also applies to C++.
When all is said and done, a class is simply another data structure. Because you can use
data structures inside of a class, it is given that you should, therefore, be able to use a
class inside of another class. Indeed, you can. Consider a class that simply stores a point:
class point
{
private:
int x;
int y;
public:
int get_x();
int get_y();
void set_x(int val);
void set_y(int val);
point();
point(int valx, int valy);
};
The guts of this class will be presented as an exercise at the end of today’s lesson. For
now, you can see that this class stores an x and a y value for a point. It also contains
access functions for getting and setting each of these values. Finally, it contains two con-
structors: one that takes no parameters, and a second one that takes an x and a y value.
If you want to create a line class, you can use the point class as a data member. A line
class can be declared as follows:
class line
{
private:
point start;
point end;
public:
point get_start();
point get_end();
void set_start(point val);
void set_end(point val);
point();
};
As you can see, this class uses points in the same way as the pointclass, presented ear-
lier, uses integers. A starting point and an ending point make up a line. The line class
defines two pointobjects as its data members. Access functions get and set these points.
Thepointobjects are used just as any other data member.

688 Bonus Day 3

38 448201x-Bonus3 8/13/02 11:19 AM Page 688

Free download pdf