Sams Teach Yourself C in 21 Days

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

BD3


you. In the timestructure, the hours, minutes, and seconds have all been stored in integer
data variables. You can change your class so that these are all stored in character vari-
ables. A character variable can be used to save a numeric value that is much higher than


  1. Because 60 is the biggest value you are storing, characters will work fine.
    What change would you make in order to implement such a change? If you are accessing
    the integer data members directly from all your programs, you must ensure that all your
    programs now pass a character value instead of an integer. If you are using access func-
    tions, you can still pass in integer values. Your access functions are all that need to
    change. They can simply convert the integer to a character and visa versa. This enables
    you to continue using your existing programs without changing them at all!
    Changing from an integer value to a character is a simplistic example. Consider a second
    example. You might have a rectangle class that stores the top-right point for the rectan-
    gle, as well as the rectangle’s width and length. You can decide to make a change to your
    class and store the top-right and bottom-left points and not store the width and length.
    Such a change would generally cause you to rewrite all the programs using the rectangle.
    By using access functions, you can continue to access the class the same way. You sim-
    ply need to make the appropriate translation in the access member functions so that two
    points are used.


DOuse classes instead of structures if
member functions are going to be
included.
DOuse access functions when possible
instead of directly accessing data mem-
bers of a class.

DON’Tdeclare anything public that
doesn’t need to be.

DO DON’T


Structures Versus Classes ....................................................................................


It bears repeating that although structures and classes are very similar, there is a differ-
ence. By default, the data members of a structure are public, which means they are
accessible outside of the structure’s member functions. The default access control for a
class is private. This means that by default, only the class’s member functions can access
the private members.

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

Free download pdf