Access Modifiers
Overview
If you build a bank application, you cannot allow any random function to write account.balance = 999999;. That data must be protected.
C++ enforces Encapsulation using Access Modifiers.
private: Data can ONLY be accessed by functions physically written inside the class.
public: Data can be accessed by anyone, anywhere in the program.
protected: Similar to private, but heavily used in Inheritance (covered later).
By absolute C++ definition, everything inside a class is completely private by default unless you explicitly label it otherwise.
Syntax
class BankAccount {
// Everything below this is locked!
private:
double balance = 0.0;
// Everything below this is open to the world!
public:
// Public method allows controlled interaction with private data
void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}
void printBalance() {
std::cout << "Balance: $" << balance << "\n";
}
};
int main() {
BankAccount myAcc;
// myAcc.balance = 1000; // FATAL COMPILER ERROR! (It is private)
myAcc.deposit(500); // Allowed! (Method is public)
myAcc.printBalance();
return 0;
}Common Pitfalls
- Making attributes
publicout of laziness. Beginners hate compiler errors, so they often make all variablespublicto make coding easier. This entirely defeats the purpose of OOP and turns your Class into a glorifiedstruct, leading to horrific, untraceable data-corruption bugs later.
Interview Questions
struct and a class in C++ regarding Access Modifiers?By default, every single member of a struct is implicitly public. By default, every single member of a class is implicitly private. Aside from this single default visibility rule, they are architecturally and mathematically identical.
Real-World Example
Protecting sensitive system configurations using private access modifiers.
#include <iostream>
class Server {
private:
int maxConnections = 100; // Locked variable
public:
// The ONLY way to alter the connection limit is through this secure channel
void upgradeServer(std::string adminPassword) {
if (adminPassword == "super_secret") {
maxConnections = 500;
std::cout << "Server Upgraded!\n";
} else {
std::cout << "Access Denied!\n";
}
}
};Check Your Knowledge
Test your understanding of Access Modifiers with these quick questions.