Encapsulation is one of the fundamental concepts of Object-Oriented Programming (OOP). It means wrapping data (variables) and code (methods) together into a single unit called a class, and restricting direct access to some of an object’s components to protect data integrity.
Use access specifiers like private, public, and protected to control access to class members.
#include <iostream>
using namespace std;
class Account {
private:
double balance; // Private variable
public:
// Constructor to initialize balance
Account(double initialBalance) {
if (initialBalance >= 0)
balance = initialBalance;
else
balance = 0;
}
// Getter function (accessor)
double getBalance() {
return balance;
}
// Setter function (mutator)
void deposit(double amount) {
if (amount > 0) {
balance += amount;
cout << "Deposited: " << amount << endl;
} else {
cout << "Invalid deposit amount." << endl;
}
}
void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
cout << "Withdrawn: " << amount << endl;
} else {
cout << "Invalid or insufficient funds." << endl;
}
}
};
int main() {
Account myAccount(1000); // Initialize with $1000
myAccount.deposit(500);
myAccount.withdraw(200);
cout << "Current Balance: $" << myAccount.getBalance() << endl;
// Direct access to balance is not possible:
// myAccount.balance = 5000; // Error: 'balance' is private
return 0;
}
private to prevent direct modification.Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!