Data Hiding Or Encapsulation
Data hiding is also known as encapsulation. It is a procedure of forming objects. An encapsulated object is often called as an abstract data type. We need to encapsulate data, because programmer often makes various mistakes and the data get changed accidentally. Thus, to protect data, we need to construct a secure and impassable wall to protect the data. Data hiding is nothing but making data variable of the class or struct private. Thus, private data cannot be accessed directly by the object. The objects using public member functions of the same class can access the private data of the class. The keywords private and protected are used for hiding the data. Table (Access Limits of class Members) shows the brief description of access specifiers. The following program explains data hiding:
8.10 Write a program to calculate simple interest. Hide the data elements of the class using private keyword.
Explanation: In the above program, the class interest is declared with the data members p_amount, float rate, period, 4, and t_amount of float type. These entire data elements are declared in private section; hence, it is hidden (encapsulated) and cannot be directly accessed by the object. Here, member functions in() is used to read data through the keyboard. The function show() is used to display the contents of the variables.
8.11 Write a program to declare class with private, public and private sections. Declare object and access data elements of these different sections.
Explanation: In the above program, the class access is declared with private, protected, and public sections. Each section holds one integer variable and one member function. The object cannot directly access the data variable and member function of the private and protected sections. The object can access only the public section of the class and through public section it can access the private or protected section. Here, the object an accesses the public variable h and initializes it with 4 whereas the private and protected variables are accessed using member functions. The function getp() and getm() are invoked by the public member function geth(). The geth() also displays the contents of the variables on the screen.