OOP: ACCESS SPECIFIERS
`protected` Access Specifier
protected is like private for outside code, but accessible inside derived classes.
You will use it mainly with inheritance.
Access Rule
| Code location | Can access protected member? |
|---|---|
| Same class | yes |
| Derived class | yes |
main() or unrelated code |
no |
Example
#include <iostream>
class Account {
protected:
double balance = 0.0;
public:
explicit Account(double initialBalance) : balance(initialBalance) {}
};
class SavingsAccount : public Account {
public:
explicit SavingsAccount(double initialBalance) : Account(initialBalance) {}
void addInterest() {
balance += balance * 0.05;
}
void display() const {
std::cout << "Balance: $" << balance << '\n';
}
};
int main() {
SavingsAccount account(1000.0);
account.addInterest();
account.display();
// account.balance = 0; // error: protected outside the class
}
Should Data Be Protected?
Use protected carefully.
Protected data can make derived classes too dependent on base class internals. Often, protected helper functions are safer than protected data.
Example:
protected:
double getBalance() const;
Viva Answer
protected members are accessible inside the class and its derived classes, but not from outside code like main(). It is mainly used with inheritance, but should be used carefully to avoid exposing too much base-class implementation to derived classes.
Quick Check
- Can
main()access protected data? - Can a derived class access protected data?
- Is protected the same as public?
- Why can protected data create tight coupling?