One of the four main pillars of Object-Oriented Programming is Encapsulation—the concept of hiding the internal state of an object and requiring all interaction to be performed through an object's methods.
In C++, encapsulation is implemented using Access Specifiers. These keywords determine who can access the variables and functions of a class.
C++ provides three access specifiers:
public: Members are accessible from outside the class. Anyone with access to the object can read or modify public members.private: Members cannot be accessed (or viewed) from outside the class. They can only be accessed by methods defined within the same class. By default, all members of a class are private if you don't specify otherwise.protected: Members cannot be accessed from outside the class, but they can be accessed by inherited classes (child classes).Good OOP design dictates that you should make your data (variables) private, and provide public functions (methods) to interact with that data. This prevents external code from accidentally corrupting the object's state.
#include <iostream>
using namespace std;
class BankAccount {
private:
// This data cannot be accessed directly from main()
double balance;
public:
// Constructor
BankAccount(double initialBalance) {
balance = initialBalance;
}
// Public method to safely modify the private data (Setter/Mutator)
void deposit(double amount) {
if (amount > 0) {
balance += amount;
cout << "Deposited: $" << amount << endl;
} else {
cout << "Invalid deposit amount!" << endl;
In the example above, if balance were public, anyone could set myAccount.balance = -9999;. By making it private and using a deposit() method, the class can validate the input (ensuring the deposit is greater than 0) before modifying the state.
private: Accessible only within the class itself (default).public: Accessible from anywhere the object is visible.protected: Accessible within the class and its derived classes.Keywords that define the accessibility or scope of the data members and member functions within a class.
Members are accessible from anywhere outside the class.
Members cannot be accessed or viewed from outside the class. This is the default in C++.
Similar to private, but members are accessible within inherited (derived) classes.
Test your understanding with 3 questions
What is the default access specifier for members of a class in C++?
Which access specifier allows members to be accessed by derived classes but not by external code?
How do you allow external code to safely modify a private variable?
2 Modules
2 Modules