Geek Slack

Learn C++
About Lesson


C++ Encapsulation


C++ Encapsulation

Encapsulation is the bundling of data (variables) and methods (functions) that operate on the data into a single unit (class), and restricting access to some of the object’s components. This protects the internal state of the object from unintended external access and modification.

1. Example of Encapsulation

Example demonstrating encapsulation using private member variables and public member functions:

#include <iostream>
#include <string>

// Class declaration
class Employee {
private:
    std::string name;
    double salary;

public:
    // Constructor
    Employee(std::string n, double s) : name(n), salary(s) {}

    // Public member function to display employee's info
    void displayInfo() {
        std::cout << "Name: " << name << ", Salary: $" << salary << std::endl;
    }

    // Public member function to increase salary
    void increaseSalary(double amount) {
        if (amount > 0) {
            salary += amount;
            std::cout << "Salary increased by $" << amount << std::endl;
        } else {
            std::cout << "Invalid amount for salary increase" << std::endl;
        }
    }
};

int main() {
    // Create object of class Employee
    Employee emp("Alice", 50000.0);

    // Display initial employee info
    std::cout << "Initial Employee Info:" << std::endl;
    emp.displayInfo();

    // Increase salary and display updated info
    emp.increaseSalary(5000.0);
    emp.displayInfo();

    return 0;
}

2. Benefits of Encapsulation

Encapsulation provides several benefits:

  • Data Hiding: Private data members cannot be accessed directly from outside the class, enhancing security and preventing unintended modifications.
  • Modularity: Classes can be developed independently and used in various parts of a program without affecting other parts, promoting code reusability.
  • Controlled Access: Access to data members is controlled through public member functions, allowing validation and enforcement of business rules.

Conclusion

Encapsulation is a fundamental principle of object-oriented programming in C++. It promotes data hiding, modularity, and controlled access to class members, leading to more robust and maintainable code. Understanding and applying encapsulation allows you to design classes that protect data integrity and provide clear interfaces for interaction with external code.

Join the conversation