CPP Tutorial



C++ ENCAPSULATION


Encapsulation in C++

Encapsulation is one of the fundamental concepts of Object-Oriented Programming (OOP). It means wrapping data (variables) and code (methods) together into a single unit called a class, and restricting direct access to some of an object’s components to protect data integrity.

Why Encapsulation?

  • Protects object data from unintended or harmful changes.
  • Controls access to the internal state of the object.
  • Improves modularity and maintainability.

How to achieve Encapsulation in C++?

Use access specifiers like private, public, and protected to control access to class members.

Example of Encapsulation:

#include <iostream>
using namespace std;

class Account {
private:
    double balance;  // Private variable

public:
    // Constructor to initialize balance
    Account(double initialBalance) {
        if (initialBalance >= 0)
            balance = initialBalance;
        else
            balance = 0;
    }

    // Getter function (accessor)
    double getBalance() {
        return balance;
    }

    // Setter function (mutator)
    void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
            cout << "Deposited: " << amount << endl;
        } else {
            cout << "Invalid deposit amount." << endl;
        }
    }

    void withdraw(double amount) {
        if (amount > 0 && amount <= balance) {
            balance -= amount;
            cout << "Withdrawn: " << amount << endl;
        } else {
            cout << "Invalid or insufficient funds." << endl;
        }
    }
};

int main() {
    Account myAccount(1000);  // Initialize with $1000

    myAccount.deposit(500);
    myAccount.withdraw(200);

    cout << "Current Balance: $" << myAccount.getBalance() << endl;

    // Direct access to balance is not possible:
    // myAccount.balance = 5000; // Error: 'balance' is private

    return 0;
}
  

Output:

Deposited: 500
Withdrawn: 200
Current Balance: $1300

Key Points to Remember:

  • Data members are kept private to prevent direct modification.
  • Public getter and setter functions control access and enforce rules.
  • Encapsulation helps maintain the internal state of the object consistently.

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review