What is Data Hiding in C++: Explanation and Example
data hiding is a technique to restrict direct access to class members by making them private or protected. It helps protect the internal state of an object and only allows controlled access through public methods.How It Works
Data hiding in C++ works by using access specifiers like private and protected to keep class data hidden from outside code. Imagine a TV remote control: you can press buttons to change channels or volume, but you cannot directly change the internal wiring. Similarly, data hiding lets you control how data is accessed or changed without exposing the data itself.
This protects the data from accidental changes or misuse. Only the class's own functions (or sometimes derived classes) can access the hidden data directly. Other parts of the program must use public functions, which act like safe doors to interact with the data.
Example
This example shows a class with a private data member and public methods to access and modify it safely.
#include <iostream> class BankAccount { private: double balance; // hidden data public: BankAccount(double initial) { if (initial < 0) { balance = 0; } else { balance = initial; } } void deposit(double amount) { if (amount > 0) { balance += amount; } } void withdraw(double amount) { if (amount > 0 && amount <= balance) { balance -= amount; } } double getBalance() const { return balance; } }; int main() { BankAccount account(100); account.deposit(50); account.withdraw(30); std::cout << "Balance: " << account.getBalance() << std::endl; // account.balance = 1000; // Error: balance is private return 0; }
When to Use
Use data hiding whenever you want to protect important data inside a class from being changed directly by other parts of your program. This is especially useful in large programs where many parts interact, to avoid bugs caused by unexpected data changes.
For example, in banking software, you want to make sure account balances cannot be set to invalid values directly. Instead, you provide controlled methods like deposit and withdraw that check the rules before changing the balance.
Key Points
- Data hiding uses
privateorprotectedaccess to restrict direct access to class data. - It protects data integrity by forcing access through controlled public methods.
- Helps prevent accidental or harmful changes to important data.
- Improves code maintainability and security.