Sams Teach Yourself C in 21 Days

(singke) #1
Polymorphism can go beyond the use just demonstrated. In fact, what has just been pre-
sented is also called function or method overloading. The key to polymorphism is that
your programs can adapt to what is sent to you. Polymorphism makes your program and
code much more reusable.

634 Bonus Day 1

Listing B1.1 is a C listing that incorporates a feature of C++. If you are using
a C++ compiler (such as Microsoft’s Visual C++ or Borland’s C++) to compile
your programs, the above listing will compile and run. If you are using an
older C compiler, you might get errors because function overloading isn’t a
supported C feature. Additionally, if you have the ANSI C flag set on your
compiler so that only ANSI C code will compile, the previous listing will not
work because this is actually an ANSI C++ feature.

Caution


There are other more appropriate examples of polymorphism that are
beyond the scope of this book. These advanced usages of polymorphism
involve having objects change their types in order to be treated as some-
thing different. For example, you can create an object that is a person and
an object that is a client. Using polymorphism you’d be able to use a client
type as if it were a person type. Again, this use of polymorphism is beyond
the scope of this book.

Note


Encapsulating It All ......................................................................................

A second characteristic of an object-oriented programming language is encapsulation.
Encapsulation enables you to create objects that are self-contained.

When combined with polymorphism, encapsulation enables you to create
Note objects that are self-sufficient, and, therefore, easy to reuse.

Encapsulation enables you to create black box functionality. Black box functionality
means that the person using your code doesn’t need to know how it works. Instead, he
only needs to know how to call the functionality and what results he will get in return.
Consider the circle example shown earlier. If you want to display a circle, all that matters
is that you know how to call the circle routines. An even better example is illustrated in
Figure B1.2.

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

Free download pdf