Topic 48 of 83
Access Modifiers
Overview
Access modifiers control who can see and modify class members. They enforce Encapsulation.
Syntax
cpp
class Security {
private:
int secretKey; // Only accessible inside this class
protected:
int accessLevel; // Accessible here AND in derived classes
public:
string username; // Accessible from anywhere
};Common Pitfalls
- Making everything `public`. This completely defeats the purpose of classes and object-oriented design.
Interview Tips
- By default, all members of a `class` in C++ are `private`. In a `struct`, all members are `public` by default.
Real-World Example
Using private variables to prevent external tampering.
example
cpp
#include <iostream>
using namespace std;
class BankAccount {
private:
double balance = 0; // Hidden from outside world
public:
void deposit(double amount) {
if (amount > 0) balance += amount;
}
double getBalance() {
return balance;
}
};
int main() {
BankAccount acc;
// acc.balance = 1000000; // ERROR: balance is private!
acc.deposit(50);
cout << acc.getBalance();
return 0;
}