Blog Details

Use the basic features of data abstraction and encapsulation in C++ programs.

To use the basic features of data abstraction and encapsulation in C++ programs, you need to understand the following concepts:


1. Data Abstraction

➤ Definition:

Hiding internal implementation details and showing only essential features of an object to the outside world.

➤ Achieved Using:

  • Classes

  • Public methods (interfaces)

  • Hiding data using private or protected access modifiers


2. Encapsulation

➤ Definition:

Wrapping data (variables) and code (methods) together as a single unit (class) and restricting direct access to some of the object's components.

➤ Achieved Using:

  • private data members

  • public getter/setter methods


Example Program: C++ - Bank Account

#include <iostream>
using namespace std;

// Class definition: Encapsulation + Abstraction
class BankAccount {
private:
    string accountHolder;  // Encapsulated data
    double balance;

public:
    // Constructor
    BankAccount(string name, double initialBalance) {
        accountHolder = name;
        balance = initialBalance;
    }

    // Getter: Abstraction
    double getBalance() {
        return balance;
    }

    // Deposit method
    void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
            cout << "Deposited: " << amount << endl;
        } else {
            cout << "Invalid deposit amount!" << endl;
        }
    }

    // Withdraw method
    void withdraw(double amount) {
        if (amount > 0 && amount <= balance) {
            balance -= amount;
            cout << "Withdrawn: " << amount << endl;
        } else {
            cout << "Insufficient balance or invalid amount!" << endl;
        }
    }

    // Show account summary (Abstraction)
    void showSummary() {
        cout << "Account Holder: " << accountHolder << endl;
        cout << "Current Balance: ₹" << balance << endl;
    }
};

// Main function
int main() {
    // Create object
    BankAccount acc("Vivek Kumar", 10000);

    // Accessing data via methods (not directly)
    acc.showSummary();
    acc.deposit(2500);
    acc.withdraw(1200);
    acc.showSummary();

    return 0;
}

Explanation:

Concept Usage in the Code
Encapsulation accountHolder and balance are private
Data Abstraction Only essential methods like deposit(), withdraw(), and getBalance() are exposed
Access Control No direct access to internal data from main()

✅ Benefits:

  • Prevents unauthorized access to internal data

  • Simplifies interface for interacting with objects

  • Easier to modify internal implementation without affecting external code


Let me know if you’d like this adapted for inheritance, polymorphism, or with file handling added!