C++ C++ Tutorial C++ Functions C++ Classes



CPP Encapsulation

Encapsulation is one of the fundamental concepts of object-oriented programming (OOP) and is a technique used to hide the internal details of an object from the outside world. In C++, encapsulation is achieved through the use of classes and access modifiers.

Encapsulation is important because it allows for better control over the data and behavior of an object. By hiding the internal details of an object, we can prevent external code from modifying the object's state in unexpected ways. This helps to ensure that the object remains in a valid state at all times.

In C++, we can use access modifiers to control the visibility of the members of a class. There are three access modifiers in C++:

  • public: Members declared as public are accessible from anywhere in the program.
  • private: Members declared as private are only accessible from within the class.
  • protected: Members declared as protected are accessible from within the class and its subclasses.

Here is an example of a class that uses encapsulation:


class BankAccount {
private:
  double balance;
public:
  void deposit(double amount) {
    balance += amount;
  }
  void withdraw(double amount) {
    if (balance >= amount) {
      balance -= amount;
    }
  }
  double getBalance() {
    return balance;
  }
};

In this example, the balance member is declared as private, which means that it can only be accessed from within the BankAccount class. The deposit and withdraw methods are declared as public, which means that they can be called from anywhere in the program. The getBalance method is also declared as public, but it only returns the value of the balance member and does not allow external code to modify it directly.

Here is an example of how we can use the BankAccount class:


BankAccount account;
account.deposit(1000);
account.withdraw(500);
double balance = account.getBalance();

In this example, we create a BankAccount object and deposit 1000 into it. We then withdraw 500 from the account and get the current balance using the getBalance method. Because the balance member is declared as private, we cannot access it directly from outside the class.

Encapsulation is an important concept in C++ and is used extensively in object-oriented programming. By hiding the internal details of an object, we can prevent external code from modifying its state in unexpected ways and ensure that it remains in a valid state at all times.

References

Activity