2.2 Encapsulation


1. Another main concept in object-oriented programming is encapsulation which refers to keeping the
object's state and behavior together.
2. Thus, the data that represents the state of the object and the functions that manipulate the data are
grouped together in one unit (the object).
3. Encapsulation can be also referred as information hiding as it allows the restriction of access to the
object's internal state, thus hiding certain details of the object's behavior.
4. In C++, as in other object-oriented programming languages, encapsulation is achieved using the by
defining a class that defines the attribute members (state) and function members (behavior) and creating
objects as instances of the class.
5. Data hiding is achieved using Access Specifiers that control a client's access to attribute and function
members.
6. There are four levels of Access Specifiers: public, private, protected and friend which are described below:
a. Public: this access specifier allows anyone to call a class's function member or to modify a data member.
The primary purpose of public members is to present to the class's clients a view of the services the
class provides.

2.2 Encapsulation


This set of services forms the public interface of the class.
The Point class definition in Listing 2.1 shows how the public specifier is used to specify the methods
move, print and is_zero as public functions.
b. Private: which is the default access mode and apply when a specifier is not explicitly included.
When a class member is set as private, it can't be accessed directly from outside the class.
In the Point class example shown in Listing 2.1, the x and y coordinate attributes are not accessible from
outside the Point class.
The values of such attributes can be manipulated using the public functions of the class.
c. Friend: this access specifier can be used to enable a class to enable certain classes and functions
specified as 'friends' to access its private members. Thus it allows the encapsulation rules to be
broken.
d. Protected: which specifies that class members can be accessed by member functions and friends of
its own class and by member functions and friends of classes derived from this class (which will be
described in more details in the next lesson).

2.2 Encapsulation




**continue next page

2.2 Encapsulation




**continue next page

2.2 Encapsulation


Listing 2.1:Point Class Definition Illustrating the use of Access Specifiers