MODULE 6: OBJECT-ORIENTED PROGRAMMING (OOP) 6.3 C++ Encapsulation & Data Hiding (Getters, Setters, Information Hiding)

Industrial reference manual: Comprehensive architectural breakdown of C++ encapsulation, data hiding mechanics, private state protection via public getters and setters, business logic validation, and 10 production-aligned real-world implementations with outputs.

šŸ›”ļø 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.

1. Secure Bank Account Encapsulation (Balance Validation)
Shields account balance inside private storage, allowing updates only through validated deposit and withdrawal setters.
C++ / Bank Account Encapsulation
#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;
}
--- Bank Account Encapsulation --- [SUCCESS]: Deposited ₹5000.00 [ERROR]: Insufficient balance or invalid withdrawal! [SUCCESS]: Withdrew ₹4000.00 Final Account Balance: ₹21000.00
2. Smart Thermostat Temperature Validation Encapsulation
Enforces a safe operating temperature range (16°C–30°C) inside a smart thermostat setter method.
C++ / Smart Thermostat Encapsulation
#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;
}
--- Smart Thermostat Encapsulation --- [SUCCESS]: Temperature set to 22.0°C [SUCCESS]: Temperature set to 25.5°C [WARNING]: Target 42°C exceeds safe limits (16°C - 30°C). Rejected! Current Thermostat Reading: 25.5°C
3. Employee Salary Privacy & Secure Modification
Protects sensitive employee compensation records from direct external tampering, allowing modifications only via authorized HR setters.
C++ / Employee Salary Encapsulation
#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;
}
--- Employee Salary Encapsulation --- [HR]: Salary updated successfully for Aarav Sharma [ERROR]: Salary below legal minimum wage threshold! [HR]: Salary updated successfully for Aarav Sharma Aarav Sharma Current Salary: ₹72000.00
4. E-Commerce Product Price Protection & Discount Rules
Ensures product prices cannot be set to negative values or zero through setter encapsulation.
C++ / Product Price Encapsulation
#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;
}
--- Product Price Encapsulation --- [ERROR]: Price cannot be negative. Price unchanged. Gaming Laptop Final Price: ₹79999.00
5. User Password Hashing & Verification Encapsulation
Encapsulates user passwords in private storage, exposing only a secure authentication verification method.
C++ / Password Security Encapsulation
#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;
}
--- Password Security Encapsulation --- Login Attempt 1 (Wrong): FAILED Login Attempt 2 (Correct): SUCCESS
6. Vehicle Speedometer & Acceleration Control Encapsulation
Shields vehicle speed state, ensuring acceleration respects vehicle speed limits and safety thresholds.
C++ / Vehicle Speedometer Encapsulation
#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;
}
--- Vehicle Speedometer Encapsulation --- Speed increased. Current: 80 km/h [SAFETY]: Max speed limit (180 km/h) enforced! Final Speedometer Reading: 180 km/h
7. Student Grade Point Average (GPA) Validation Encapsulation
Encapsulates student exam scores, validating that GPA inputs fall strictly between 0.0 and 10.0.
C++ / Student GPA Encapsulation
#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;
}
--- Student GPA Encapsulation --- [SUCCESS]: GPA updated for Priya Singh [ERROR]: Invalid GPA score (11.2). Must be between 0.0 and 10.0. [SUCCESS]: GPA updated for Priya Singh Priya Singh Final GPA: 9.2
8. Hospital Patient Blood Pressure Monitoring Encapsulation
Shields patient vital sign parameters behind clinical validation setters.
C++ / Patient Vitals Encapsulation
#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;
}
--- Patient Vitals Encapsulation --- Patient Systolic BP: 135 mmHg
9. Inventory Stock Warehouse Threshold Encapsulation
Encapsulates warehouse stock inventory counts to prevent negative inventory allocations.
C++ / Warehouse Stock Encapsulation
#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;
}
--- Warehouse Stock Encapsulation --- [STOCK]: Inventory adjusted by -5. Current: 10 [ERROR]: Stock depletion exceeds available inventory! Final Stock Units: 10
10. Smartphone Battery Charging State Encapsulation
Manages smartphone battery percentage (0%–100%) securely using encapsulated setter methods.
C++ / Smartphone Battery Encapsulation
#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;
}
--- Smartphone Battery Encapsulation --- Battery charged. Current level: 75% Battery charged. Current level: 100% Final Battery Level: 100%