Access modifiers
- C++ course
- Intermediate
- Lesson 5/116
- 5 min
Learn the differences between public, private and protected.
Access modifiers
C++ has three access modifiers: public, private and protected. They control how class members can be reached from outside. A colon follows the modifier: public:.
public members can be accessed from anywhere. private members can be accessed only from the class's own member functions. protected is like private but deriving classes can also access it. Until a modifier is written, members are private by default.
private for encapsulation
private protects internal data from outside interference. This technique is called encapsulation. Member variables are made private and exposed through public member functions.
Example: class Account { int balance; public: int getBalance() { return balance; } };. Here balance cannot be changed directly from outside; it can only be read via getBalance. This prevents invalid states such as a negative balance.
Practice Define the Account class with access modifiers
Define an Account class. First int balance; (default private), then under public: add void setBalance(int b) { balance = b; } and int getBalance() { return balance; }. In main create an instance, call setBalance(100) and print the result of getBalance() with std::cout.
Starter code
#include <iostream>
// Define the Account class here
int main() {
// Create an Account instance, call setBalance and print getBalance
return 0;
}Sample solution
#include <iostream>
class Account {
int balance;
public:
void setBalance(int b) {
balance = b;
}
int getBalance() {
return balance;
}
};
int main() {
Account acc;
acc.setBalance(100);
std::cout << acc.getBalance();
return 0;
}Expected output
100
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match each modifier to its access level
| Term | Meaning |
|---|---|
public |
Access from anywhere |
private |
Only inside the class |
protected |
Deriving classes also access |
class Light { }; |
Default private |
2 Which of the following is true?
class Account { int balance; public: void deposit(int x); };- balance is accessible from outside
- deposit is accessible from outside Correct answer
- deposit is treated as private
- balance is treated as public
Explanation: deposit is under public:, so it can be called from outside.
3 Write the access modifier
class Account { ____: int getBalance(); };
class Account { public: int getBalance(); };
Explanation: Members under public: are accessible from outside.