Access Modifiers
Access modifiers in C++ are keywords used to set the access level of class members (variables and functions). They control who can access the members of a class from outside or inside the class.
There are three main access modifiers in C++:
public are accessible from anywhere in the program where the object is visible.class Student {
public:
int rollNo; // Can be accessed directly
void display() {
cout << rollNo;
}
};
private are accessible only inside the class.class Student {
private:
int marks; // Cannot be accessed from outside
public:
void setMarks(int m) {
marks = m;
}
int getMarks() {
return marks;
}
};
In this example, marks can only be accessed using setMarks() and getMarks().
protected are like private, but they can also be accessed in derived (child) classes.class Person {
protected:
string name;
};
class Student : public Person {
public:
void setName(string n) {
name = n; // Allowed because name is protected
}
};
| Access Modifier | Accessible Within Class | Accessible Outside Class | Accessible in Derived Class |
|---|---|---|---|
public |
Yes | Yes | Yes |
private |
Yes | No | No |
protected |
Yes | No | Yes |
Using access modifiers properly makes the code more secure, organized, and easier to manage.
Open this section to load past papers