| Lesson 4 || Encapsulation |
| Objective || Mechanism behind packaging data |
Encapsulation and packaging Data and Behavior of an ADT in C++
Mechanism behind packaging data and ADT behavior
C++ provides the encapsulation mechanism to implement ADTs. Encapsulation packages both the internal implementation details of the type and the externally available operations and
functions that can act on variables of that type. The implementation details can be made inaccessible to code that uses the type. Code that uses the ADT is called the client code for the ADT.
For example, a stack could be implemented as a fixed-length array, while the publicly available operations would include push and pop.Changing the internal implementation to a linked list should not affect how push and pop are used externally.
Encapsulating the data and behavior of the stack keeps the implementation of the stack hidden from its clients, which means the client code using the stack will not need to be rewritten if the stack implementation changes.
A class is a type that you define, as opposed to the types, such as int and char, that are already defined for you. A value for a class type is the set of values of the member variables.
The interface of an ADT tells you how to use the ADT in your program. When you define an ADT as a C++ class, the interface consists of the public member functions of the class along with the comments that tell you how to use
the public member functions. The interface of the ADT should be all you need to know in order to use the ADT in your program.
The implementation of the ADT explains how this interface is realized as C++ code. The implementation of the ADT consists of the private members of the class and the definitions of both the public and private member functions.
Although you need the implementation in order to run a program that uses the ADT, you should not need to know anything about the implementation in order to write the rest of a program that uses the ADT;
that is you should not need to know anything about the implementation in order to write the main part of the program and to write any nonmember functions used by the main part of the program.