C++
Access modifiers
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.
Exercise 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.
Show example 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;
}
Test yourself
-
Match each modifier to its access level
- public
- Access from anywhere
- private
- Only inside the class
- protected
- Deriving classes also access
- class Light { };
- Default private
-
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
- deposit is treated as private
- balance is treated as public
Show answer
deposit is accessible from outside — deposit is under public:, so it can be called from outside.
-
Write the access modifier
class Account { ____: int getBalance(); };
Show answer
class Account { public: int getBalance(); };
Next lesson: Summary - Classes