encapsulation


Concept: encapsulation

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

Key Characteristics

Access Specifiers

C++ uses three access specifiers to implement encapsulation:

  1. Public: Members are accessible from outside the class
  2. Private: Members are only accessible within the class
  3. Protected: Members are accessible within the class and its derived classes

Example 1: Basic Encapsulation with Public and Private

#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;
}

Explanation:

Example 2: Protected Members and Inheritance

#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;
}

Explanation:

Example 3: Getter and Setter Methods

#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;
}

Explanation:

Additional Considerations

Summary

Encapsulation in C++ is a powerful concept that combines data and methods into a single unit, controlling access through public, private, and protected specifiers:

  1. Public members are accessible from anywhere.
  2. Private members are only accessible within the class.
  3. Protected members are accessible within the class and its derived classes.

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.

Related

Previous Page | Course Schedule | Course Content