Encapsulation

Encapsulation is one of the key features of object-oriented programming. It involves the bundling of data members and functions inside a single class.

Bundling similar data members and functions inside a class together also helps in data hiding.

Encapsulation is a process of wrapping similar code in one place. we can bundle data members and functions that operate together inside a single class.

For example

class Rectangle {

  public:

    int length;

    int breadth;

    int getArea() {

      return length * breadth;

    }

};




Program:

#include <iostream>
using namespace std;

class SportsTeam {
private:
    string teamName;
    string coachName;
    int totalPlayers;
    int matchesWon;

public:
    // Constructor to initialize team details
    SportsTeam(string name, string coach, int players) {
        teamName = name;
        coachName = coach;
        totalPlayers = players;
        matchesWon = 0; // Initialize matches won to 0
    }

    // Setter methods to update team details (Encapsulation)
    void setTeamName(string name) {
        teamName = name;
    }

    void setCoachName(string coach) {
        coachName = coach;
    }

    void setTotalPlayers(int players) {
        if (players > 0)
            totalPlayers = players;
        else
            cout << "Number of players must be positive!" << endl;
    }

    void recordMatchWin() {
        matchesWon++;
    }

    // Getter methods to access private members (Encapsulation)
    string getTeamName() const {
        return teamName;
    }

    string getCoachName() const {
        return coachName;
    }

    int getTotalPlayers() const {
        return totalPlayers;
    }

    int getMatchesWon() const {
        return matchesWon;
    }

    // Display team details
    void displayTeamInfo() const {
        cout << "Team Name: " << teamName << endl;
        cout << "Coach Name: " << coachName << endl;
        cout << "Total Players: " << totalPlayers << endl;
        cout << "Matches Won: " << matchesWon << endl;
    }
};
int main() {
    // Create a SportsTeam object
    SportsTeam team("Punjab Kings", "Ricky Ponting", 11);

    // Display initial team details
    cout << "Initial Team Details:" << endl;
    team.displayTeamInfo();

    // Update team details
    team.setCoachName("Ricky Ponting");
    team.recordMatchWin();
    team.recordMatchWin();

    // Display updated team details
    cout << "\nUpdated Team Details:" << endl;
    team.displayTeamInfo();
    return 0;
}


Output:

Initial Team Details:

Team Name: Punjab Kings

Coach Name: Ricky Ponting

Total Players: 11

Matches Won: 0


Updated Team Details:

Team Name: Punjab Kings

Coach Name: Ricky Ponting

Total Players: 11

Matches Won: 2


Process returned 0 (0x0)   execution time : 1.195 s

Press any key to continue.



Data Hiding

Data hiding is a way of restricting the access of our data members by hiding the implementation details. Encapsulation also provides a way for data hiding.

Data hiding is a fundamental concept of object-oriented programming where class members (data) are made private to prevent direct access from outside the class.

We can use access modifiers to achieve data hiding in C++. For example,

 

#include <iostream>

#include <string>

using namespace std;


class BankAccount {

private:

    string accountHolderName; // Hidden data

    double balance;           // Hidden data


public:

    // Constructor to initialize account details

    BankAccount(string name, double initialBalance) {

        accountHolderName = name;

        if (initialBalance >= 0) {

            balance = initialBalance;

        } else {

            balance = 0;

            cout << "Initial balance cannot be negative. Setting balance to Rs.0." << endl;

        }

    }


    // Public method to deposit money

    void deposit(double amount) {

        if (amount > 0) {

            balance += amount;

            cout << "Deposited: Rs." << amount << endl;

        } else {

            cout << "Deposit amount must be positive!" << endl;

        }

    }


    // Public method to withdraw money

    void withdraw(double amount) {

        if (amount > 0 && amount <= balance) {

            balance -= amount;

            cout << "Withdrawn: Rs." << amount << endl;

        } else if (amount > balance) {

            cout << "Insufficient balance!" << endl;

        } else {

            cout << "Withdrawal amount must be positive!" << endl;

        }

    }


    // Public method to check balance

    double getBalance() const {

        return balance;

    }


    // Public method to display account details

    void displayAccountInfo() const {

        cout << "Account Holder: " << accountHolderName << endl;

        cout << "Current Balance: Rs." << balance << endl;

    }

};

int main() {

    // Create a BankAccount object

    BankAccount account("Prasanjeet", 500.0);


    // Display initial account info

    account.displayAccountInfo();


    // Perform some transactions

    account.deposit(200);

    account.withdraw(100);

    account.withdraw(700); // Attempt to withdraw more than balance


    // Display updated account info

    account.displayAccountInfo();

    return 0;

}


Output:

Account Holder: Prasanjeet

Current Balance: Rs.500

Deposited: Rs.200

Withdrawn: Rs.100

Insufficient balance!

Account Holder: Prasanjeet

Current Balance: Rs.600


Process returned 0 (0x0)   execution time : 2.442 s

Press any key to continue.








No comments:

Post a Comment