C++ Encapsulation
Encapsulation is an object-oriented programming concept in C++ that combines data (attributes) and methods (functions) into a single unit called a class. It also restricts direct access to some of the object’s components using access specifiers, which helps protect data integrity and improves code maintainability.
Key Points of Encapsulation
- Encapsulation is achieved by making data members private and providing public getter and setter functions.
- It improves data security and ensures controlled access to object properties.
- Encapsulation is a fundamental principle of object-oriented programming.
Next Topic
Next, learn about Inheritance in C++.
- Data members of a class are usually declared private to hide them from outside access.
- Public member functions (getters and setters) are used to access and modify private data safely.
- Encapsulation ensures data hiding and prevents accidental modification of sensitive data.
Example: Encapsulation in C++
#include <iostream>
using namespace std;
class BankAccount {
private:
double balance; // Private data member
public:
// Setter to deposit or set balance
void setBalance(double b) {
if(b >= 0)
balance = b;
else
cout << "Invalid balance!" << endl;
}
// Getter to access balance
double getBalance() {
return balance;
}
};
int main() {
BankAccount account;
account.setBalance(1000.50); // Set balance using setter
cout << "Current Balance: $" << account.getBalance() << endl;
account.setBalance(-500); // Invalid attempt
cout << "Balance after invalid attempt: $" << account.getBalance() << endl;
return 0;
}
Output
Current Balance: $1000.5 Invalid balance! Balance after invalid attempt: $1000.5
Important Notes
- Encapsulation is achieved by making data members private and providing public getter and setter functions.
- It improves data security and ensures controlled access to object properties.
- Encapsulation is a fundamental principle of object-oriented programming.
Next Topic
Next, learn about Inheritance in C++.