OOP

Data Encapsulation

In object-oriented programming (OOP), data encapsulation is a fundamental principle that combines data (attributes) and the methods (functions) that operate on that data into a single unit called a class. This bundling serves two key purposes:

  1. Data Protection: It restricts direct access to the data members of an object, preventing them from being modified accidentally or maliciously by external code.
  2. Information Hiding: It hides the internal implementation details of the class, allowing you to control how the data is accessed and manipulated. This promotes modularity and maintainability of code.

How Encapsulation Works in C++

C++ implements encapsulation using access modifiers:

Example:

class Account {
private:
    double balance; // Private data member

public:
    // Public constructor to initialize balance
    Account(double initialBalance) : balance(initialBalance) {}

    // Public method to deposit funds (controlled access)
    void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
        } else {
            // Handle invalid deposit attempt (e.g., throw an exception)
        }
    }

    // Public method to get the balance (read-only access)
    double getBalance() const {
        return balance;
    }
};

Explanation:

  1. The Account class encapsulates the balance data member (private) and two methods: deposit and getBalance.
  2. The balance member is protected from direct modification outside the class.
  3. The deposit method allows controlled addition of funds while handling invalid input.
  4. The getBalance method provides a read-only view of the balance.

Benefits of Data Encapsulation

By following these principles, you can create more robust, secure, and maintainable object-oriented programs in C++.

Understanding Encapsulation: Practice Questions

To understand the topic well try to answer following questions.

1. Access and Modification:

2. Information Hiding:

3. Benefits and Trade-offs:

4. Alternative Access Levels:

5. Real-World Application: