capypad
0 day streak
cpp / beginner
Snippet

Access Modifiers: Controlling Visibility

Access modifiers control who can see and use class members. Private members can only be accessed within the class itself, while public members can be accessed from anywhere. Here, balance is private to prevent direct modification from outside. Instead, other code must use the deposit() function, which can validate the input and protect the data's integrity.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class BankAccount {
private:
double balance;
public:
string owner;
BankAccount(string o, double b) {
owner = o;
balance = b;
}
double getBalance() {
return balance;
}
void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}
};
 
int main() {
BankAccount account("Max", 1000.0);
account.deposit(500.0);
cout << account.getBalance() << endl;
return 0;
}
Breakdown
1
private:
Makes balance hidden from outside the class
2
public:
Makes owner accessible from anywhere
3
double getBalance()
Public getter to safely retrieve the private balance
4
void deposit(double amount)
Public method to modify balance with validation