Access Modifiers
Access Modifiers in C++
Access modifiers control the visibility and accessibility of class members, forming the foundation of encapsulation in OOP.
1. Introductionâ
C++ provides three access specifiers:
publicprotectedprivate
Default Behavior:
classâ members areprivateby defaultstructâ members arepublicby default
2. Publicâ
Accessible from anywhere.
Example:
#include <iostream>
using namespace std;
class Student {
public:
string name;
void display() {
cout << "Name: " << name << endl;
}
};
int main() {
Student s;
s.name = "Alice";
s.display();
return 0;
}
3. Privateâ
Accessible only within the same class.
Example:
#include <iostream>
using namespace std;
class BankAccount {
private:
double balance;
public:
BankAccount(double initial) : balance(initial) {}
void deposit(double amount) {
if (amount > 0) balance += amount;
}
double getBalance() const {
return balance;
}
};
int main() {
BankAccount acc(1000);
acc.deposit(500);
cout << "Balance: " << acc.getBalance() << endl;
return 0;
}
4. Protectedâ
Accessible within the class and derived classes.
Example:
#include <iostream>
using namespace std;
class Vehicle {
protected:
int speed = 0;
public:
void accelerate(int inc) { speed += inc; }
};
class Car : public Vehicle {
public:
void showSpeed() {
cout << "Speed: " << speed << " km/h\n";
}
};
int main() {
Car c;
c.accelerate(80);
c.showSpeed();
return 0;
}
5. Summary Tableâ
| Specifier | Same Class | Derived Class | Outside Class |
|---|---|---|---|
public | Yes | Yes | Yes |
protected | Yes | Yes | No |
private | Yes | No | No |
6. Friend Functions & Classesâ
friend keyword bypasses access rules.
class Box {
private:
int length;
public:
friend void printLength(Box b);
};
void printLength(Box b) {
cout << "Length: " << b.length << endl;
}
7. Relationship with Inheritanceâ
Access modifiers affect how base class members are inherited (see Inheritance documentation).
8. Best Practicesâ
- Make data members
privateby default. - Provide public getters/setters or methods.
- Use
protectedonly when needed for inheritance. - Minimize use of
friend. - Follow const-correctness.
These two files are now ready for download.
Telemetry Integration
Completed working through this block? Sync progress to workspace.