Encapsulation is a mechanism that binds together data and functions that manipulate a single logical unit. It keeps the data safe from any external interference and misuse. In other words, Encapsulation is the wrapping up of data and related functions in a single unit called class. The only way to access the data is through the function, which is wrapped in the class. These functions prepare the class’s interfaces through which the outside world (other classes) can access them.
Consider two classes. Library class and a Student class. The Library class encapsulates data (like bookid, bookauthor, booktitle, no_of_copies) and functions (like issue(), book_status() and book description ()) into a single unit as shown in figure. Similarly, the Student class encapsulates data and functions, as shown in the figure.
The two classes are independent of each other. The Student class has no details about the Library class, so it cannot directly access a book’s details. However, if a student wants to access some information about a book from a Library class, they can indirectly access it using the Library class’s appropriate function.
The technique shown in the above example is the comer stone of OOP (Object Oriented Programming). It gives the programmer who defined the total class control over what attributes (data) are accessed and how they are manipulated and displayed.
In C++, the concept of Encapsulation is implemented using a class. Data and Functions of a class may be private or public. Private data or function of a class cannot be accessed from outside the class, and public data or functions of a class can be accessed from anywhere (other classes). Normally data of a class is private, so it cannot be accessed by function outside the class, reducing data misuse. A class’s public functions should be coded carefully to protect data from accidental manipulation by outside function.
With Encapsulation, data hiding can be accomplished. Data hiding can be defined as a mechanism of hiding the data Of a class from the outside world (other classes) so that any access to it either intentionally or unintentionally can’t modify the data. Data hiding can be achieved by making the data of a class private.
Advantages of Encapsulation in C++ :
The following are the advantages of Encapsulation:
• It protects the data of a class from accidental manipulation or misuse by the functions outside the class.
• Any changes made in the data and functions of a class do not affect other classes.
• Classes are independent of each other. Therefore, each class can be appropriately studied for a better understanding of the design.