Expert C Programming

(Jeff_L) #1
changing the user interface without affecting any users.

Notice that many of the software attributes are "shoulds." OOP languages like C++ provide the
features needed to move these goals from being a desired state to an easily-accomplished fact.
Abstraction is useful in software because it allows the programmer to:



  • hide irrelevant detail, and concentrate on essentials.

  • present a "black box" interface to the outside world. The interface specifies the valid
    operations on the object, but does not indicate how the object will implement them internally.

  • break a complicated system down into independent components. This in turn localizes
    knowledge, and prevents undisciplined interaction between components.

  • reuse and share code.


C supports abstraction through allowing the user to define new types (struct, enum) that are
almost as convenient as the predefined types (int, char, etc. ), and to use them in a similar way.
We say "almost as convenient" because C does not allow the predefined operators (*, <<, [], +
etc.) to be redefined for user-defined types. C++ removes this barrier. C++ also provides automatic
and controlled initialization, cleanup at the end of data's lifetime, and implicit type conversion. All of
this is either missing from C, or not present in so convenient a form.


Abstraction creates an abstract data type, and C++ uses the class feature to implement it. This is a
view from the top down, looking at the attributes of data types. It is also possible to approach this
from the bottom up, and view it in terms of encapsulation: grouping together the various data and
methods that implement a type.


Encapsulation—Grouping Together Related Types, Data, and Functions


When you bundle together an abstract data type with its operations, it is termed "encapsulation". Non-
OOP languages don't have adequate mechanisms for doing this. There is no way to tell a C compiler,
"These three functions are the only valid operations on this particular struct type." There is no way to
prevent a programmer from defining additional functions that access the struct in an unchecked or
inconsistent manner.


Software Dogma


The Key Idea— A Class Encapsulates (Bundles Together) Code with Its Related Data


When programming first evolved, assembler programs could only operate on bits and
words. As high-level languages developed, they provided easy access to the growing variety
of hardware operands: floats, doubles, longs, chars, and so on. Some high-level languages
enforced strong typing to ensure that only operations appropriate to a variable's type could
be done. This was a rudimentary form of class, as it tied together data items with the
permissible operations on them. The operations were typically restricted to individual

Free download pdf