Encapsulation is one of the four fundamental Object-Oriented Programming (OOP) concepts. In C++, it refers to the bundling of data and the methods that operate on that data within a single unit or object. Encapsulation is implemented using classes and access specifiers (public, private, and protected).
C++ uses three access specifiers to implement encapsulation:
#include <iostream>
#include <string>
class BankAccount {
private:
std::string accountHolder;
double balance;
public:
BankAccount(const std::string& name, double initialBalance)
: accountHolder(name), balance(initialBalance) {}
void deposit(double amount) {
if (amount > 0) {
balance += amount;
std::cout << "Deposited: $" << amount << std::endl;
}
}
void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
std::cout << "Withdrawn: $" << amount << std::endl;
} else {
std::cout << "Insufficient funds or invalid amount" << std::endl;
}
}
void displayBalance() const {
std::cout << "Account Holder: " << accountHolder << std::endl;
std::cout << "Current Balance: $" << balance << std::endl;
}
};
int main() {
BankAccount account("John Doe", 1000.0);
account.deposit(500.0);
account.withdraw(200.0);
account.displayBalance();
// account.balance = 1000000; // This would cause a compilation error
return 0;
}
accountHolder
and balance
are private, protecting them from direct external access.deposit
, withdraw
, displayBalance
) provide controlled access to the private data.#include <iostream>
#include <string>
class Shape {
protected:
double area;
public:
Shape() : area(0) {}
virtual void calculateArea() = 0;
void displayArea() const {
std::cout << "Area: " << area << std::endl;
}
};
class Circle : public Shape {
private:
double radius;
public:
Circle(double r) : radius(r) {}
void calculateArea() override {
area = 3.14159 * radius * radius;
}
};
class Rectangle : public Shape {
private:
double length;
double width;
public:
Rectangle(double l, double w) : length(l), width(w) {}
void calculateArea() override {
area = length * width;
}
};
int main() {
Circle circle(5);
circle.calculateArea();
circle.displayArea();
Rectangle rectangle(4, 6);
rectangle.calculateArea();
rectangle.displayArea();
return 0;
}
area
is protected, allowing access in derived classes (Circle
and Rectangle
).area
member.displayArea
) can be used by derived classes.radius
, length
, width
) are encapsulated within those classes.#include <iostream>
#include <string>
class Employee {
private:
std::string name;
int age;
double salary;
public:
Employee(const std::string& n, int a, double s)
: name(n), age(a), salary(s) {}
// Getter methods
std::string getName() const { return name; }
int getAge() const { return age; }
double getSalary() const { return salary; }
// Setter methods
void setName(const std::string& n) { name = n; }
void setAge(int a) {
if (a > 0 && a < 120) age = a;
else std::cout << "Invalid age" << std::endl;
}
void setSalary(double s) {
if (s >= 0) salary = s;
else std::cout << "Invalid salary" << std::endl;
}
void displayInfo() const {
std::cout << "Name: " << name << ", Age: " << age
<< ", Salary: $" << salary << std::endl;
}
};
int main() {
Employee emp("Alice", 30, 50000);
emp.displayInfo();
emp.setAge(31);
emp.setSalary(55000);
emp.displayInfo();
emp.setAge(-5); // This will print an error message
return 0;
}
name
, age
, salary
) are encapsulated.Encapsulation in C++ is a powerful concept that combines data and methods into a single unit, controlling access through public, private, and protected specifiers:
Key benefits of encapsulation: - Data protection and controlled access - Improved maintainability and flexibility - Support for data abstraction - Enhanced code organization and modularity
Best practices: - Keep data members private whenever possible - Use public methods to provide controlled access to private data - Implement getter and setter methods for fine-grained control - Use protected members judiciously in inheritance hierarchies
Encapsulation is fundamental to object-oriented design in C++, promoting robust and maintainable code by hiding implementation details and exposing only necessary interfaces to the outside world.