Sams Teach Yourself C in 21 Days

(singke) #1
Person brad: Bradley Jones
age: 21
Person blank: blank blank
age: -1
Listing B3.7 presents a relatively simple class called person. Additionally, in
lines 36–53, a main()routine is provided that instantiates two personobjects.
An object called bradis instantiated in line 40. This object is constructed with values.
The age for the bradobject is also set in the following line to a nice wishful 21. In line
43, a second object called blankis instantiated. The blankobject uses all default values
in its construction. In the output, you can see that all the default values are printed.
In looking at the base class in lines 6–34, note a few new items. Many of the public
member functions of the personclass have their code directly after the declaration. For
example, in line 12, the set_fname()function has the code—a simple call to the string
copy function—right after its declaration. This is equivalent to declaring an inline func-
tion. When a routine is short, it is easier and clearer to simply declare it inline within the
class. If a member function is a bit longer, such as get_name()in line 15, it is best to
declare it outside the class definition. The get_name()function is declared in lines
27–34.
This listing has a few other items that you were not presented with in earlier listings. In
line 2, the string.h header file is included. This was for the string copy and string catena-
tion functions used within the listing. In line 4, a constant was defined for the maximum
length being used.

692 Bonus Day 3

OUTPUT

ANALYSIS

You should note that there is no error checking in this listing. There is noth-
ing that prevents a name from being longer than 81 characters. Such error-
checking logic has been left out of these examples to help keep them short.

Caution


The Protected Access Data Modifier ............................................................


The most important change you should notice in Listing B3.7 is in line 7. The keyword
protectedis being used. You should have expected the keyword privateto be used. As
you learned yesterday, using privatekeeps other parts of a listing from accessing data
members or values. If you are going to implement inheritance, you may want to let these
private values be accessed directly by the classes that inherit from this base class. To do
this, you use the protectedkeyword. The protectedkeyword will only let the current
class and classes that inherit the current class access the values.

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

Free download pdf