next up previous contents
Next: Inheritance Up: Features of Object-Oriented Programming Previous: Features of Object-Oriented Programming

Data Encapsulation

Data encapsulation, sometimes referred to as data hiding, is the mechanism whereby the implementation details of a class are kept hidden from the user. The user can only perform a restricted set of operations on the hidden members of the class by executing special functions commonly called methods. The actions performed by the methods are determined by the designer of the class, who must be careful not to make the methods either overly flexible or too restrictive. This idea of hiding the details away from the user and providing a restricted, clearly defined interface is the underlying theme behind the concept of an abstract data type.

The advantage of using data encapsulation comes when the implementation of the class changes but the interface remains the same. For example, to create a stack class which can contain integers, the designer may choose to implement it with an array, which is hidden from the user of the class. The designer then writes the push() and pop() methods which puts integers into the array and removes them from the array respectively. These methods are made accessible to the user. Should an attempt be made by the user to access the array directly, a compile time error will result. Now, should the designer decide to change the stack's implementation to a linked list, the array can simply be replaced with a linked list and the push() and pop() methods rewritten so that they manipulate the linked list instead of the array. The code which the user has written to manipulate the stack is still valid because it was not given direct access to the array to begin with.

The concept of data encapsulation is supported in C++ through the use of the public, protected and private keywords which are placed in the declaration of the class. Anything in the class placed after the public keyword is accessible to all the users of the class; elements placed after the protected keyword are accessible only to the methods of the class or classes derived from that class; elements placed after the private keyword are accessible only to the methods of the class.

As a convention, calling a method of an object instantiated from a class is commonly referred to as sending a message to that object.


next up previous contents
Next: Inheritance Up: Features of Object-Oriented Programming Previous: Features of Object-Oriented Programming

Donald Craig
Sat Jul 13 16:02:11 NDT 1996