Sams Teach Yourself C in 21 Days

(singke) #1
a birthday structure and an anniversary structure, which both have month, day, and year
values called month,day, andyear. Each of these structures could also have similarly
named functions such as a display_date()function. By including the structure name in
the function definition (as is done in Listing B3.3), you can associate the appropriate
function definition with the correct structure.

674 Bonus Day 3

Just like the data members, the function members can only be used in the
context of the structure. If you try to use a member function outside of
another member function from the same structure, you must include the
structure name. If you don’t use the structure name, you will get an error.

Note


Using Classes ......................................................................................................


Although you may not have realized it, you have already been using classes in your C++
programs. A structure is a specialized form of a class. You’ll learn more about this in a
few minutes.
classis another keyword that is available in C++. Like the structkeyword, the class
keyword enables you to create your own user-defined data types. You create a class in the
same way as you create a structure. Earlier you created a new data type called time,
which was a structure. The timestructure could have been declared as follows instead:
class time {
int hours;
int minutes;
int seconds;
};
Now instead of being defined as a structure, the timedata type is defined as a class. This
only required that you use the classkeyword instead of the structkeyword. In addition
to the data values, the member functions added in Listing B3.3 can also be declared as
part of the timeclass.
Unlike declaring a structure, using a class to declare objects doesn’t require you to
include the classkeyword. The class name is all you need. This is, in essence, equiva-
lent to having declared a structure with a typedef. To declare the end_timeand
start_timedata elements with the timestructure, you do the following:
struct time start_time;
struct time end_time;

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

Free download pdf