Data hiding helps keep important information safe inside a class. It stops other parts of the program from changing data by mistake.
0
0
Data hiding in C++
Introduction
When you want to protect sensitive information in a program.
When you want to control how data is accessed or changed.
When you want to make your program easier to fix and update.
When you want to hide complex details from users of your class.
Syntax
C++
class ClassName { private: int hiddenData; // This data is hidden public: void setData(int value) { hiddenData = value; } int getData() { return hiddenData; } };
private: means data or functions can only be used inside the class.
public: means data or functions can be used anywhere.
Examples
This class hides the length variable and allows access only through setLength and getLength.
C++
class Box { private: int length; public: void setLength(int l) { length = l; } int getLength() { return length; } };
The name is hidden and can only be changed or read using the public functions.
C++
#include <string> class Person { private: std::string name; public: void setName(std::string n) { name = n; } std::string getName() { return name; } };
Sample Program
This program hides the balance inside the BankAccount class. You can only change it by depositing or withdrawing money. This keeps the balance safe from wrong changes.
C++
#include <iostream> using namespace std; class BankAccount { private: double balance; public: BankAccount() { balance = 0.0; } void deposit(double amount) { if (amount > 0) { balance += amount; } } void withdraw(double amount) { if (amount > 0 && amount <= balance) { balance -= amount; } } double getBalance() { return balance; } }; int main() { BankAccount myAccount; myAccount.deposit(1000); myAccount.withdraw(250); cout << "Current balance: $" << myAccount.getBalance() << endl; return 0; }
OutputSuccess
Important Notes
Data hiding helps prevent bugs by controlling how data is changed.
Use getter and setter functions to access hidden data safely.
Private data cannot be accessed directly from outside the class.
Summary
Data hiding keeps important data safe inside a class.
Use private to hide data and public functions to access it.
This makes programs safer and easier to manage.