Encapsulation vs Information Hiding - Rybd04/2143-OOP GitHub Wiki

Definition

Encapsulation vs Information Hiding

Information hiding is a specific aspect of encapsulation where you hide the internal details of a class from the outside world. It means that users of the class should not need to know about its internal workings, just how to use it.

Explanation

This is like if you worked at KFC and they gave you all of the herbs and spices and told you how to mix them, but never told you what they were.

Basic Code Example

#include <iostream>
using namespace std;

class BankAccount {
private:
    double balance;  // Private data member, hidden from outside

public:
    // Public method to access and modify balance
    void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
        }
    }

    // Public method to access balance safely
    double getBalance() {
        return balance;
    }
};

int main() {
    BankAccount account;
    account.deposit(1000);  // Adding money to the account
    cout << "Balance: $" << account.getBalance() << endl;  // Accessing balance safely

    // The following line would be an error because balance is private:
    // cout << account.balance << endl;

    return 0;
}

Image

image

Additional Resources

https://stackoverflow.com/questions/13913174/what-are-the-differences-between-information-hiding-and-encapsulation https://www.tutorialspoint.com/difference-between-data-hiding-and-encapsulation

⚠️ **GitHub.com Fallback** ⚠️