Sams Teach Yourself C in 21 Days

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

BD3


Using a class, you do the following:
time start_time;
time end_time;
This is pretty straightforward. You should note that when you use a class to declare a
new data item, you are actually declaring an object. In other words, in C++ an objectis
simply a declared data item created by using a class. Both start_timeandend_timeare
objects created using the timeclass.
Remember, although a structure is a specialized type of class, there are differences.
Before looking at what is different in Listing B3.3 using classes instead of structures,
first look at the key difference between classes and structures. This difference lies in the
default method to access data in a structure versus the default method in a class.

You use a class to create an object. When you use a class to create an object,
you are instantiatingthe class. Instantiation is simply creating an instance of
a class.

Note


Controlling Access to Data in a Class ..........................................................


Within a class—and hence a structure—you can determine which routines have access to
data by using one of three additional keywords that are a part of C++. These keywords
are:


  • public

  • private

  • protected
    By default, the members of a class are private. This includes both the data members
    and the member functions. For structures, the default access is public. This difference is
    significant.


Public Data
If data is declared as public, it is accessible not only by member functions within the
class or structure, but also by any external source within your program. If you have a
structure such as
struct name {
string firstname;
string lastname;
string formatted_name();
}

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

Free download pdf