Sams Teach Yourself C in 21 Days

(singke) #1
Object-Oriented Programming Languages 631

BD1


The Object-Oriented Constructs ........................................................................


You have already learned that an object-oriented language works with objects. What
exactly are these objects? There are three key features that help to define the objects of
an object-oriented programming language. It is the implementation of these features that
make a language object oriented. These constructs are


  • Polymorphism

  • Encapsulation

  • Inheritance
    Some people also consider reuse as the fourth feature that helps define an object-oriented
    programming language. Reuse is simply the capability to use the same code easily in
    multiple programs without substantial rewriting. If you effectively implement the three
    key features, you will automatically obtain reuse.


One of the reasons developers prefer an OOP language to a procedural lan-
guage, such as C, is the factor of reuse. Although you can reuse functions
and libraries in C, this does not give the power provided by the reuse of
classes and templates. You’ll learn about classes in Bonus Day 3, “Working
with C++ Classes and Objects.”

Note


Adapting with Polymorphism ......................................................................

The first trait of an object-oriented programming language is polymorphism. Po l ymeans
many and morphmeans form. A polymorphic program is one that can take many forms.
In other words, the program is able to adapt automatically. Consider an example. If you
were asked to draw a circle, what facts would you need to know? If you were given the
center point and a point on the circle, you’d be able to draw the circle. Additionally, if
you were given three points that were on the circle, you’d be able to draw it. If you were
given the radius and the center point, you’d have a third way of drawing a circle. Figure
B1.1 illustrates these methods for drawing a circle.
If you are writing a C program to draw a circle, you could include three different func-
tions in order to adapt to the different ways a user might want to draw a circle. You could
also create three uniquely named functions such as
draw_circle_with_points(int x1, int y1, int x2, int y2, int x3, int y3);
draw_circle_with_radius(int ctrX, int ctrY, long radius);
draw_circle_with_center_and_point(int ctrX, int ctrY, int x1, int y1);

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

Free download pdf