Skillversitas

Encapsulation and Access Modifiers

Encapsulation is a core concept in object-oriented programming that hides implementation details from users and exposes only the necessary interface. With encapsulation, a class's data members are protected from direct access from outside, so data integrity is better preserved.

Access modifiers in C++ consist of public, private, and protected. Each one controls the level of access to class members. public can be accessed from anywhere, private only from within the class, and protected from within the class as well as from derived classes.

Code Example

#include <iostream>
#include <string>
using namespace std;

class Employee {
private:
    string name;
    double salary;
    int age;

public:
    Employee(string empName, double empSalary, int empAge) {
        name = empName;
        setSalary(empSalary);
        age = empAge;
    }

    string getName() {
        return name;
    }

    void setName(string empName) {
        if (!empName.empty()) {
            name = empName;
        }
    }

    double getSalary() {
        return salary;
    }

    void setSalary(double empSalary) {
        if (empSalary >= 0) {
            salary = empSalary;
        } else {
            cout << "Salary must not be negative!" << endl;
            salary = 0;
        }
    }

    int getAge() {
        return age;
    }

    void setAge(int empAge) {
        if (empAge >= 17 && empAge <= 65) {
            age = empAge;
        } else {
            cout << "Age is not valid!" << endl;
        }
    }

    void displayInfo() {
        cout << "Name: " << name << endl;
        cout << "Salary: " << salary << endl;
        cout << "Age: " << age << " years" << endl;
    }
};

int main() {
    Employee emp("David Brown", 5000000, 28);
    emp.displayInfo();

    cout << "\nChanging employee data..." << endl;
    emp.setSalary(7500000);
    emp.setAge(30);
    emp.displayInfo();

    cout << "\nTrying to set a negative salary..." << endl;
    emp.setSalary(-1000000);

    cout << "\nTrying to set an age below 17 years..." << endl;
    emp.setAge(15);

    return 0;
}

Code Explanation

  1. private: string name, double salary, int age - The data members are private. They cannot be accessed directly from outside the class, like emp.salary = 5000. This is the heart of encapsulation.

  2. public: string getName() - A getter (accessor). It returns the value of a private data member to the caller. Getters are usually read-only.

  3. public: void setSalary(double empSalary) - A setter (mutator). It changes the value of a private data member. Setters allow validating data before it is stored.

  4. if (empSalary >= 0) - The validation inside the setter ensures the salary is not negative. If the data is invalid, the value is not changed or is set to a default.

  5. emp.setSalary(7500000) - Changes the data through the setter. This is a safe way because the data has been validated first.

  6. emp.setSalary(-1000000) - An attempt to set a negative salary is rejected by the validation inside the setter.

  7. Getters and setters are public so they can be accessed from outside to read or change data in a controlled way.

Everyday Use Cases

Imagine a bank ATM. You cannot withdraw money from an ATM machine without first entering your PIN. The PIN is protected (private) data. The bank provides a safe way (public interface) to access your balance and make transactions. You cannot directly change the balance in the bank's database, but you must go through the defined procedures (deposit, withdraw, transfer).

Conclusion

Encapsulation protects class data from uncontrolled direct access. Use private for data that needs protection, public for interfaces that users can access, and protected for data that also needs to be accessed by derived classes. Getters and setters are the main mechanism for safely reading and changing data with the necessary validation.