Access Modifiers - Kamills-12/2143-OOP GitHub Wiki
Access Modifiers
Kade Miller
What Are Access Modifiers?
Access modifiers control who can see or use data in your class.
They’re all about visibility and protection.
You’ve got 3 main ones in C++:
Public
Anyone can access it inside the class or from outside (like in main()
).
class Player {
public:
int score;
void sayHi() {
cout << "Hi!" << endl;
}
};
int main() {
Player p;
p.score = 100; // allowed
p.sayHi(); // allowed
}
---
## Private
class BankAccount {
private:
double balance;
public:
void deposit(double amount) {
balance += amount;
}
double getBalance() {
return balance;
}
};
int main() {
BankAccount b;
// b.balance = 9999; not allowed
b.deposit(1000); // allowed
}
---
## Protected
class Animal {
protected:
string name;
};
class Dog : public Animal {
public:
void setName(string n) {
name = n; // allowed in child class
}
};
int main() {
Dog d;
// d.name = "Rex"; not allowed here
d.setName("Rex"); // works through method
}