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:
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.
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