Access modifiers in C++ determine how the members (data and functions) of a class can be accessed. There are three main types of access modifiers in C++:
- Public: Members are accessible from outside the class.
- Private: Members are only accessible from within the class.
- Protected: Members are accessible from within the class and its derived (inherited) classes.
1. Public Access Modifier
Any member declared as public
can be accessed from anywhere in the code (both inside and outside the class).
#include <iostream>
using namespace std;
class Person {
public:
string name;
void setName(string n) {
name = n;
}
void display() {
cout << "Name: " << name << endl;
}
};
int main() {
Person person1;
person1.setName("Alice");
person1.display(); // Accessible due to public
return 0;
}
Explanation:
name
,setName
, anddisplay
arepublic
, so they can be accessed and modified outside the class, like in themain()
function.
2. Private Access Modifier
Any member declared as private
can only be accessed within the class itself. These members cannot be accessed directly from outside the class.
#include <iostream>
using namespace std;
class BankAccount {
private:
double balance;
public:
BankAccount() {
balance = 0.0;
}
void deposit(double amount) {
if (amount > 0) {
balance += amount;
cout << "Deposited: " << amount << endl;
}
}
void showBalance() {
cout << "Balance: " << balance << endl;
}
};
int main() {
BankAccount account;
account.deposit(500); // Works
account.showBalance(); // Works
// account.balance = 1000; // Error: balance is private
return 0;
}
Explanation:
- The
balance
variable isprivate
, so it can’t be accessed or modified directly from outside the class. You can only change it through public methods likedeposit()
and view it usingshowBalance()
.
3. Protected Access Modifier
Members declared as protected
behave like private
but are accessible to any derived (inherited) class.
#include <iostream>
using namespace std;
class Employee {
protected:
int salary;
public:
void setSalary(int s) {
salary = s;
}
};
class Developer : public Employee {
public:
void showSalary() {
cout << "Salary: " << salary << endl; // Accessible in derived class
}
};
int main() {
Developer dev;
dev.setSalary(50000); // Accessible via public method
dev.showSalary(); // Works
// dev.salary = 60000; // Error: salary is protected
return 0;
}
Explanation:
salary
isprotected
, meaning it cannot be accessed directly from themain()
function, but it can be accessed within the derived classDeveloper
.
Summary
- Public: Accessible everywhere (inside and outside the class).
- Private: Accessible only within the class.
- Protected: Accessible within the class and its derived classes.
By understanding access modifiers, you can control how your class members are exposed and used in your program, ensuring encapsulation in your code.