Data Encapsulation
Data encapsulation is one of the core principles of Object-Oriented Programming. It means combining data (variables) and functions (methods) that work on that data into a single unit—a class. It also involves hiding the internal details of how the class works and only allowing controlled access to the data.
class BankAccount {
private:
int balance; // Private data member
public:
void setBalance(int amount) {
if (amount >= 0) {
balance = amount;
}
}
int getBalance() {
return balance;
}
};
In this example:
balance is private, so it cannot be accessed or changed directly from outside.setBalance() and getBalance() are public functions that control how the balance is changed or viewed.private: Only accessible within the class.public: Accessible from outside the class.protected: Accessible in the class and derived classes.Encapsulation helps keep code safe, clean, and well-structured, which is especially important in large or complex projects.
Open this section to load past papers