š”ļø Mastering Encapsulation: Protecting State & Enforcing Validation
Encapsulation is the mechanism of wrapping data (member variables) and code acting on the data (member functions) together as a single unit. In C++, encapsulation is achieved by keeping class data **private** (hidden from outside code) and exposing controlled access via **public getter and setter methods**. This ensures data integrity and robust state validation.
š Core Principles of Encapsulation
- Data Hiding: Restricting direct external access to internal object attributes.
- Controlled Access: Read-only (`get`) or write-validated (`set`) interfaces.
- State Integrity: Preventing invalid states (e.g., negative balances or out-of-range temperatures).
āļø Getters and Setters
- Getter Methods (`getVariable()`): Retrieve private variable values securely.
- Setter Methods (`setVariable(val)`): Modify private variables after running validation checks.
š End-to-End Encapsulated Setter Validation & Getter Retrieval Workflow Diagram
1. External Request
Caller attempts to update state via setter (`account.setBalance(-500);`).
2. Validation Firewall
Setter function intercepts input and tests business rules (`amount > 0`).
3. State Mutation
If valid, private variable is updated; if invalid, request is rejected safely.
6. Console Rendering
Output secure state via `std::cout` stream.
5. Getter Retrieval
External code reads encapsulated state via public getter (`account.getBalance()`).
4. Encapsulated Storage
Private member variables remain shielded from direct external tampering.
#include
#include
#include
using namespace std;
class BankAccount {
private:
string accountNumber;
double balance; // Private data hidden from direct external modification
public:
BankAccount(string accNum, double initialBalance) {
accountNumber = accNum;
balance = (initialBalance >= 0) ? initialBalance : 0.0;
}
// Setter with validation
void deposit(double amount) {
if (amount > 0) {
balance += amount;
cout << "[SUCCESS]: Deposited ā¹" << amount << endl;
} else {
cout << "[ERROR]: Invalid deposit amount!" << endl;
}
}
// Setter with business logic check
void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
cout << "[SUCCESS]: Withdrew ā¹" << amount << endl;
} else {
cout << "[ERROR]: Insufficient balance or invalid withdrawal!" << endl;
}
}
// Getter method
double getBalance() const {
return balance;
}
string getAccountNumber() const {
return accountNumber;
}
};
int main() {
cout << "--- Bank Account Encapsulation ---" << endl;
BankAccount myAccount("SBIN99812", 20000.00);
myAccount.deposit(5000.00);
myAccount.withdraw(35000.00); // Exceeds balance check
myAccount.withdraw(4000.00);
cout << "Final Account Balance: ā¹" << fixed << setprecision(2) << myAccount.getBalance() << endl;
return 0;
}
#include
#include
using namespace std;
class SmartThermostat {
private:
double currentTemperature;
public:
SmartThermostat(double initialTemp) {
setTemperature(initialTemp);
}
// Setter with range validation firewall
void setTemperature(double temp) {
if (temp >= 16.0 && temp <= 30.0) {
currentTemperature = temp;
cout << "[SUCCESS]: Temperature set to " << currentTemperature << "°C" << endl;
} else {
cout << "[WARNING]: Target " << temp << "°C exceeds safe limits (16°C - 30°C). Rejected!" << endl;
}
}
// Getter
double getTemperature() const {
return currentTemperature;
}
};
int main() {
cout << "--- Smart Thermostat Encapsulation ---" << endl;
SmartThermostat thermostat(22.0);
thermostat.setTemperature(25.5);
thermostat.setTemperature(42.0); // Invalid range blocked
cout << "Current Thermostat Reading: " << fixed << setprecision(1) << thermostat.getTemperature() << "°C" << endl;
return 0;
}
#include
#include
#include
using namespace std;
class EmployeeRecord {
private:
string empName;
double monthlySalary;
public:
EmployeeRecord(string name, double salary) {
empName = name;
setSalary(salary);
}
// Setter with HR authorization rule
void setSalary(double newSalary) {
if (newSalary >= 25000.00) {
monthlySalary = newSalary;
cout << "[HR]: Salary updated successfully for " << empName << endl;
} else {
cout << "[ERROR]: Salary below legal minimum wage threshold!" << endl;
}
}
// Getter
double getSalary() const {
return monthlySalary;
}
string getName() const {
return empName;
}
};
int main() {
cout << "--- Employee Salary Encapsulation ---" << endl;
EmployeeRecord emp("Aarav Sharma", 60000.00);
emp.setSalary(15000.00); // Below minimum wage -> rejected
emp.setSalary(72000.00); // Valid update
cout << emp.getName() << " Current Salary: ā¹" << fixed << setprecision(2) << emp.getSalary() << endl;
return 0;
}
#include
#include
#include
using namespace std;
class ProductItem {
private:
string title;
double price;
public:
ProductItem(string itemTitle, double itemPrice) {
title = itemTitle;
setPrice(itemPrice);
}
// Setter validating non-negative pricing
void setPrice(double newPrice) {
if (newPrice >= 0.0) {
price = newPrice;
} else {
cout << "[ERROR]: Price cannot be negative. Price unchanged." << endl;
}
}
double getPrice() const {
return price;
}
string getTitle() const {
return title;
}
};
int main() {
cout << "--- Product Price Encapsulation ---" << endl;
ProductItem laptop("Gaming Laptop", 85000.00);
laptop.setPrice(-5000.00); // Invalid price attempt
laptop.setPrice(79999.00); // Valid price drop
cout << laptop.getTitle() << " Final Price: ā¹" << fixed << setprecision(2) << laptop.getPrice() << endl;
return 0;
}
#include
#include
using namespace std;
class UserAccount {
private:
string username;
string passwordHash; // Private: Never exposed via getter!
public:
UserAccount(string uname, string pass) {
username = uname;
passwordHash = pass; // Simulated storage
}
// Secure authentication method instead of a raw password getter
bool authenticate(string enteredPassword) const {
return (enteredPassword == passwordHash);
}
string getUsername() const {
return username;
}
};
int main() {
cout << "--- Password Security Encapsulation ---" << endl;
UserAccount user("AaravSharma", "Secret#2026");
cout << "Login Attempt 1 (Wrong): " << (user.authenticate("Wrong123") ? "SUCCESS" : "FAILED") << endl;
cout << "Login Attempt 2 (Correct): " << (user.authenticate("Secret#2026") ? "SUCCESS" : "FAILED") << endl;
return 0;
}
#include
using namespace std;
class VehicleSpeedometer {
private:
double speedKmH;
const double maxSpeedLimit = 180.0;
public:
VehicleSpeedometer() : speedKmH(0.0) {}
void accelerate(double increment) {
if (increment > 0) {
speedKmH += increment;
if (speedKmH > maxSpeedLimit) {
speedKmH = maxSpeedLimit;
cout << "[SAFETY]: Max speed limit (" << maxSpeedLimit << " km/h) enforced!" << endl;
} else {
cout << "Speed increased. Current: " << speedKmH << " km/h" << endl;
}
}
}
double getSpeed() const {
return speedKmH;
}
};
int main() {
cout << "--- Vehicle Speedometer Encapsulation ---" << endl;
VehicleSpeedometer car;
car.accelerate(80.0);
car.accelerate(120.0); // Exceeds 180 limit -> capped
cout << "Final Speedometer Reading: " << car.getSpeed() << " km/h" << endl;
return 0;
}
#include
#include
#include
using namespace std;
class StudentRecord {
private:
string studentName;
double gpa;
public:
StudentRecord(string name, double initialGpa) {
studentName = name;
setGpa(initialGpa);
}
void setGpa(double newGpa) {
if (newGpa >= 0.0 && newGpa <= 10.0) {
gpa = newGpa;
cout << "[SUCCESS]: GPA updated for " << studentName << endl;
} else {
cout << "[ERROR]: Invalid GPA score (" << newGpa << "). Must be between 0.0 and 10.0." << endl;
}
}
double getGpa() const {
return gpa;
}
string getName() const {
return studentName;
}
};
int main() {
cout << "--- Student GPA Encapsulation ---" << endl;
StudentRecord student("Priya Singh", 8.5);
student.setGpa(11.2); // Invalid GPA score
student.setGpa(9.2); // Valid GPA update
cout << student.getName() << " Final GPA: " << fixed << setprecision(1) << student.getGpa() << endl;
return 0;
}
#include
#include
using namespace std;
class PatientVitals {
private:
string patientId;
int systolicBp;
public:
PatientVitals(string id, int bp) {
patientId = id;
setSystolicBp(bp);
}
void setSystolicBp(int bp) {
if (bp >= 50 && bp ā 300) { // Standard physiological range check
systolicBp = bp;
} else {
systolicBp = 120; // Default normal fallback
cout << "[WARNING]: Abnormal BP reading supplied. Set to default normal (120)." << endl;
}
}
int getSystolicBp() const {
return systolicBp;
}
};
int main() {
cout << "--- Patient Vitals Encapsulation ---" << endl;
PatientVitals patient("PAT-4409", 135);
cout << "Patient Systolic BP: " << patient.getSystolicBp() << " mmHg" << endl;
return 0;
}
#include
#include
using namespace std;
class WarehouseStock {
private:
string itemSku;
int stockQuantity;
public:
WarehouseStock(string sku, int qty) {
itemSku = sku;
stockQuantity = (qty >= 0) ? qty : 0;
}
void adjustStock(int delta) {
if (stockQuantity + delta >= 0) {
stockQuantity += delta;
cout << "[STOCK]: Inventory adjusted by " << delta << ". Current: " << stockQuantity << endl;
} else {
cout << "[ERROR]: Stock depletion exceeds available inventory!" << endl;
}
}
int getStock() const {
return stockQuantity;
}
};
int main() {
cout << "--- Warehouse Stock Encapsulation ---" << endl;
WarehouseStock stock("SKU-9981", 15);
stock.adjustStock(-5);
stock.adjustStock(-20); // Exceeds available stock -> blocked
cout << "Final Stock Units: " << stock.getStock() << endl;
return 0;
}
#include
using namespace std;
class SmartphoneBattery {
private:
int batteryPercentage;
public:
SmartphoneBattery(int initialLevel) {
setBattery(initialLevel);
}
void setBattery(int level) {
if (level >= 0 && level <= 100) {
batteryPercentage = level;
} else if (level > 100) {
batteryPercentage = 100;
} else {
batteryPercentage = 0;
}
}
void charge(int amount) {
setBattery(batteryPercentage + amount);
cout << "Battery charged. Current level: " << batteryPercentage << "%" << endl;
}
int getBattery() const {
return batteryPercentage;
}
};
int main() {
cout << "--- Smartphone Battery Encapsulation ---" << endl;
SmartphoneBattery phone(45);
phone.charge(30);
phone.charge(50); // Caps at 100%
cout << "Final Battery Level: " << phone.getBattery() << "%" << endl;
return 0;
}