From what are we hiding the data? |
You're misunderstanding data hiding. When you declare variables as private in a class, you're not hiding the data from other programs, you're hiding the data from other classes and code in YOUR program.
As other have explained, by providing interfaces in your class, you are providing controlled methods by which the private variables in your class can be modified. Compare this with a global variable that can be modified willy-nilly all over your program. That is a nightmare to maintain.
if i write two classes: Class a and class b. Why would i write code in class b which creates unnecessary problems to my class a data members? |
You wouldn't (or shouldn't). The fact that you're asking the question, indicates that you understand why you should not do that.
We see all the time on this forum where a begginner has made his class variables public either because he is too lazy to properly encapsulate them, or doesn't understand why he should do so.
Megatron 0 wrote: |
---|
In my experience with classes and objects, I often hide data from myself so I cause less errors when reading/writing data in memory. |
Bingo.
Megatron 0's pin code example is a situation where data
should be encrypted within a class. In an ATM or POS device, the class representing the pin pad should accept the digits entered by the user and immediately encrypt them, storing only the encrypted pin within the class. The clear pin should never be stored within the device to prevent it being discovered by memory scraping malware (aka the Target hack). Ensuring the pin is always encrypted and is only accessed through a known interface is easy if it is stored in a private variable in a class representing the pin pad (or even a class representing just the pin) and the only access is to the encrypted pin via public methods of the class.