Sams Teach Yourself C in 21 Days

(singke) #1
employee::employee( char fn[], char ln[])
Theemployeeconstructor accepts a first name and a last name. In line 27, you can see
that if the first or last name is left off, the default value of eblankis passed to the func-
tion.
When constructing an employee, you are actually creating a personand then construct-
ing the employee. When the constructor for the employee class is called, a call to the
constructor of the base class,person, is made first. After the person constructor has exe-
cuted, the subclass’s constructor is executed. The object isn’t considered constructed
until both constructors are executed successfully. Listing B3.9 will help illustrate this
later in today’s lesson.
In Listing B3.8, you want to pass the values sent to the employeeconstructor through to
thepersonconstructor. To do this, you add the values to the end of the constructor’s
header line, as shown in line 46. As you can see in line 46, the first name and last name
values are sent to the personconstructor.
In line 48, the employeeconstructor initializes salaryvalue to 0. When this is com-
pleted, the first name and last name will be set to the values set when the employee
object is instantiated, or eblankif nothing is passed. The age will be set to [ms] 1 as ini-
tialized in the personconstructor, and the salarywill be initialized to 0.

Using the Subclass
In line 68 of Listing B3.8, an employee object called kyleis instantiated. In this case
“Kyle”and“Rinne”are passed to the constructor of the class. In line 69, the
set_salary()member function of the employeeclass is called. In line 70, you can see
that the set_age()member function can also be used. Even though set_age()is a part
ofperson, it is declared as public, so the subclass,employee, can use the function as if it
were its own. In lines 72–74, you can see that the access functions can be used to print
out the appropriate values as well.

Constructors and Destructors Revisited ........................................................


Previously, it was stated that constructors for subclasses still call the base class’s con-
structor. The same is true of destructors. For destructors, first the subclass is called and
then the base class. Using the employeeclass, the employeedestructor code is executed
first, and then the persondestructor code is executed. Listing B4.3 is a short listing that
illustrates this order by printing a simple message in each of the functions. You can
review this code and its output.

696 Bonus Day 3

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

Free download pdf