Introduction
Encapsulation is one of the fundamental principles of Object-Oriented Programming (OOP). It is the concept of bundling data and methods that operate on that data within a single unit, typically a class. Encapsulation restricts direct access to some of an object’s components, which is a means of preventing unintended interference and misuse. Instead, access to the data is usually provided through public methods, which enforce controlled interaction with the object’s data.
Benefits of Encapsulation
- Improved Code Maintenance: Encapsulation helps keep code modular and easier to manage. Changes in one part of the code can be made independently of other parts.
- Enhanced Security: By restricting access to internal data, encapsulation helps protect the integrity of the object’s state.
- Increased Flexibility: Encapsulation allows for the modification of the internal implementation without affecting other parts of the program.
Implementing Encapsulation in C++
Private Members
Class members are typically made private to hide them from outside access.
Public Methods
Public methods (getters and setters) are used to provide controlled access to private members.
Example: Encapsulation in C++
#include <iostream>
using namespace std;
class BankAccount {
private:
string accountHolder;
double balance;
public:
// Constructor
BankAccount(string name, double initialBalance) {
accountHolder = name;
balance = initialBalance;
}
// Getter for accountHolder
string getAccountHolder() {
return accountHolder;
}
// Getter for balance
double getBalance() {
return balance;
}
// Method to deposit money
void deposit(double amount) {
if (amount > 0) {
balance += amount;
} else {
cout << "Invalid deposit amount!" << endl;
}
}
// Method to withdraw money
void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
} else {
cout << "Invalid or insufficient amount!" << endl;
}
}
};
int main() {
// Create a BankAccount object
BankAccount account("John Doe", 1000.0);
// Deposit money
account.deposit(500.0);
cout << "Balance after deposit:
quot; << account.getBalance() << endl; // Withdraw money account.withdraw(300.0); cout << "Balance after withdrawal:
quot; << account.getBalance() << endl; // Attempt invalid withdrawal account.withdraw(1500.0); cout << "Final balance:
quot; << account.getBalance() << endl; return 0; }
Output
Balance after deposit: $1500
Balance after withdrawal: $1200
Invalid or insufficient amount!
Final balance: $1200
Explanation
- The
BankAccount
class has private membersaccountHolder
andbalance
. - Public methods (
getAccountHolder
,getBalance
,deposit
,withdraw
) provide controlled access to these private members. - The
main
function demonstrates creating aBankAccount
object, depositing and withdrawing money, and handling invalid operations.
Encapsulation with Getter and Setter() Methods
Getter and setter methods are commonly used to access and update the values of private data members. They allow for validation and control over how data is accessed or modified.
Example: Using Getters and Setters
#include <iostream>
using namespace std;
class Student {
private:
string name;
int age;
public:
// Constructor
Student(string n, int a) {
name = n;
age = a;
}
// Getter for name
string getName() {
return name;
}
// Setter for name
void setName(string n) {
name = n;
}
// Getter for age
int getAge() {
return age;
}
// Setter for age
void setAge(int a) {
if (a > 0) {
age = a;
} else {
cout << "Invalid age!" << endl;
}
}
// Method to display student details
void display() {
cout << "Name: " << name << ", Age: " << age << endl;
}
};
int main() {
// Create a Student object
Student student("Alice", 20);
// Display initial details
student.display();
// Update name and age
student.setName("Bob");
student.setAge(22);
// Display updated details
student.display();
// Attempt to set invalid age
student.setAge(-5);
student.display();
return 0;
}
Output
Name: Alice, Age: 20
Name: Bob, Age: 22
Invalid age!
Name: Bob, Age: 22
Explanation
- The
Student
class has private membersname
andage
. - Getter and setter methods (
getName
,setName
,getAge
,setAge
) provide controlled access and modification of these members. - The
setAge
method includes validation to prevent invalid age values.
Real-World Example: Encapsulation in a Library Management System
Example: Library Management System
#include <iostream>
using namespace std;
class Book {
private:
string title;
string author;
int copiesAvailable;
public:
// Constructor
Book(string t, string a, int copies) {
title = t;
author = a;
copiesAvailable = copies;
}
// Getter for title
string getTitle() {
return title;
}
// Getter for author
string getAuthor() {
return author;
}
// Getter for copiesAvailable
int getCopiesAvailable() {
return copiesAvailable;
}
// Method to borrow a book
void borrowBook() {
if (copiesAvailable > 0) {
copiesAvailable--;
cout << "Book borrowed successfully!" << endl;
} else {
cout << "No copies available!" << endl;
}
}
// Method to return a book
void returnBook() {
copiesAvailable++;
cout << "Book returned successfully!" << endl;
}
// Method to display book details
void display() {
cout << "Title: " << title << ", Author: " << author << ", Copies Available: " << copiesAvailable << endl;
}
};
int main() {
// Create a Book object
Book book("1984", "George Orwell", 5);
// Display initial details
book.display();
// Borrow a book
book.borrowBook();
book.display();
// Return a book
book.returnBook();
book.display();
// Attempt to borrow a book when no copies are available
for (int i = 0; i < 6; i++) {
book.borrowBook();
}
book.display();
return 0;
}
Output
Title: 1984, Author: George Orwell, Copies Available: 5
Book borrowed successfully!
Title: 1984, Author: George Orwell, Copies Available: 4
Book returned successfully!
Title: 1984, Author: George Orwell, Copies Available: 5
Book borrowed successfully!
Book borrowed successfully!
Book borrowed successfully!
Book borrowed successfully!
Book borrowed successfully!
No copies available!
Title: 1984, Author: George Orwell, Copies Available: 0
Explanation
- The
Book
class has private memberstitle
,author
, andcopiesAvailable
. - Public methods (
getTitle
,getAuthor
,getCopiesAvailable
,borrowBook
,returnBook
,display
) provide controlled access and modification of these members. - The
main
function demonstrates borrowing and returning books, as well as handling the scenario when no copies are available.
Conclusion
Encapsulation is a fundamental concept in C++ that helps to protect the internal state of an object and ensures controlled access to its data. By using private members and public methods (getters and setters), you can enforce validation and control how data is accessed or modified. Understanding and implementing encapsulation effectively is crucial for creating robust, maintainable, and secure software.