Sams Teach Yourself C in 21 Days

(singke) #1
By encapsulating data and functionality, you create black box functionality. You have
created an object that not only stores the circle’s data (its center point and radius) but that
also knows how to draw the circle onscreen. The benefit is that you can reuse these black
boxes without having to know how their internals work. This level of reuse also enables
you to change the implementation of the functionality without having to change any of
the calling programs.

636 Bonus Day 1

On Bonus Day 3, “Working with C++ Classes and Objects,” you will learn
about classes and objects. Classes enable you to encapsulate data and func-
tionality in an object-oriented programming language such as C++, Java, or
C#.

Note


Pulling from the Past with Inheritance ..........................................................

The third characteristic of an object-oriented programming language is inheritance.
Inheritance is the capability to create new objects that expand the characteristics of exist-
ing objects. Consider the square functionality discussed earlier. A square object can con-
tain the following information:


  • Top-left corner point

  • Length of side

  • The character with which to draw the square

  • A function to return the area of the square
    If you know the top-left corner and the length of the side, you can draw the square. A
    function to return the area of the square can be encapsulated within the square object as
    well.
    Using inheritance, you can extend the square into a cube object. Actually, the cube object
    inherits from the square object. All of the characteristics of the square object become a
    part of the cube. The cube object modifies the existing area function to return the area of
    the cube instead of the area of the square; however, everything else can be used directly
    from the square object. A person using the cube object doesn’t really need to know the
    square is involved (see Figure B1.3).


OOP in Action ..............................................................................................

To help illustrate the three object-oriented programming concepts, a small C++ program
is presented in Listing B1.2. This listing is provided to help you see that a C++ listing
does not look exactly like a C listing. During the next few days, the code in this listing
will become clearer.

36 448201x-Bonus1 8/13/02 11:18 AM Page 636

Free download pdf