Sams Teach Yourself C in 21 Days

(singke) #1
Working with C++ Classes and Objects 673

BD3


In lines 20–24, you can see that this new listing starts out in the same way as the previ-
ous listing does. In line 25, you see the first real difference—the use of one of the mem-
ber functions. As you can see in line 25, member functions are used in the same way as
data members. The member operator (.) is used to access the function in the same for-
mat as a data member. Remember, to access a data member in a structure, you use the
format
structure_name.data_member_name
Accessing a member function is done the same way:
structure_name.member_function_name([passed_values])
You might wonder why the structure name isn’t passed to the add...andprint_time()
functions. Each member function is associated with a specific declaration of the struc-
ture, just as the data members are. When using the member function, you will generally
be specifying which timestructure you’re using. For example, in line 25, you are calling
theprint_time()function within the start_time timestructure. In line 27, you are
calling the print_time()function in the end_time timestructure. Because you know
which declaration of the structure you are using, you don’t need to pass the structure’s
address.
You’ll notice that in the actual add...functions, you also don’t need to specify which
structure is being used (see line 68). Because there is a specific instance of the structure
being called, the compiler assumes that you are using the same structure. This is the
same reason the data members don’t need to be preceded by the structure name as well.

Defining Member Functions
Because more than one structure could have member functions with the same name, you
need to associate the member functions with the structure when you are defining them.
As you can see in Listing B3.3, this is accomplished by using a slightly different format
for the function headers when defining the functions. In line 52, you can see the
add_hour()function header. As you can see, the structure name followed by two colons
is used before the actual function name. This additional code associates the function to
the structure.
The general structure for defining a member function is
return_value class_name::member_function_name( parameters)
{
// function body
}
Remember, you need to include the structure name in this way because you could have
multiple structures with the same member function names. For example, you could have

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

Free download pdf