Home » What is Data hiding

What is Data hiding

by Online Tutorials Library

What is Data hiding?

Data hiding is a technique of hiding internal object details, i.e., data members. It is an object-oriented programming technique. Data hiding ensures, or we can say guarantees to restrict the data access to class members. It maintains data integrity.

Data hiding means hiding the internal data within the class to prevent its direct access from outside the class.

If we talk about data encapsulation so, Data encapsulation hides the private methods and class data parts, whereas Data hiding only hides class data components. Both data hiding and data encapsulation are essential concepts of object-oriented programming. Encapsulation wraps up the complex data to present a simpler view to the user, whereas Data hiding restricts the data use to assure data security.

Data hiding also helps to reduce the system complexity to increase the robustness by limiting the interdependencies between software components. Data hiding is achieved by using the private access specifier.

Example: We can understand data hiding with an example. Suppose we declared an Account class with a data member balance inside it. Here, the account balance is sensitive information. We may allow someone to check the account balance but won’t allow altering the balance attribute. So, by declaring the balance attribute private, we can restrict the access to balance from an outside application.

Now, let’s discuss the access specifiers to understand the data hiding. Access specifiers define how the member’s functions and variables can be accessed from outside the class. So, there are three access specifiers available within a class that are stated as follows:

Private members/methods: Functions and variables declared as private can be accessed only within the same class, and they cannot be accessed outside the class they are declared.

Public members/methods: Functions and variables declared under public can be accessed from anywhere.

Protected members/methods: Functions and variables declared as protected cannot be accessed outside the class except a child class. This specifier is generally used in inheritance.

Now let’s see an example of data hiding in C++.

Example

In this example, there is a class with a variable and two functions. Here, the variable “num” is private so, it can be accessed only by the members of the same class, and it can’t be accessed anywhere else. Hence, it is unable to access this variable outside the class, which is called data hiding.

Output

Enter any Integer value  2  The value is 2  

Now, you would have understood the data hiding and how to implement it in C++.


You may also like