Encapsulation is the principle of hiding the implementation details of a class from other parts of the program, and providing a well-defined interface for accessing and manipulating the data and behavior of the class. Encapsulation is important in object-oriented programming because it allows for better code organization, modularity, and maintainability.
C++ supports encapsulation through the use of access specifiers such as public, private, and protected. These access specifiers control the visibility of class members (data and functions) to other parts of the program.
Public members are accessible from anywhere in the program, including from outside the class. Private members are only accessible from within the class, and cannot be accessed from outside the class. Protected members are similar to private members, but can be accessed by derived classes.
Here is an example of a simple C++ class that demonstrates encapsulation through the use of access specifiers:
#include <iostream>
class BankAccount {
private:
int accountNumber;
double balance;
public:
BankAccount(int acctNum, double bal) : accountNumber(acctNum), balance(bal) {}
double getBalance() { return balance; }
void deposit(double amount) { balance += amount; }
void withdraw(double amount) { balance -= amount; }
};
int main() {
BankAccount myAccount(123456, 1000.0);
std::cout << "Initial balance: $" << myAccount.getBalance() << std::endl;
myAccount.deposit(500.0);
std::cout << "New balance: $" << myAccount.getBalance() << std::endl;
myAccount.withdraw(200.0);
std::cout << "New balance: $" << myAccount.getBalance() << std::endl;
return 0;
}
In this example, we define a BankAccount class that has two private data members, accountNumber and balance, and three public member functions, getBalance(), deposit(), and withdraw(). The private data members can only be accessed from within the class, while the public member functions provide a well-defined interface for accessing and manipulating the data.
The main() function creates an instance of the BankAccount class and calls its public member functions to deposit and withdraw money from the account. Because the private data members are encapsulated, they cannot be accessed directly from outside the class, ensuring that the account balance is only modified through the public member functions.
In summary, C++ supports encapsulation through the use of access specifiers such as public, private, and protected. Encapsulation is important in object-oriented programming because it allows for better code organization, modularity, and maintainability by hiding the implementation details of a class and providing a well-defined interface for accessing and manipulating its data and behavior.