Index
Access Modifier
Access modifiers are keywords that determine the accessibility of members (variables and methods) of a class. They control how and where the members of a class can be accessed from within the code. There are three primary access modifiers in C++:
- public
2. private
3. protected
1. ‘public’ Access Modifier
Description:
- Members declared as
publicare accessible from anywhere in the program. This means they can be accessed by any other class, function, or piece of code outside the class.
Use Case:
- Use
publicfor methods or data members that should be accessible to the outside world, like an interface.
Example:
class MyClass {
public:
int publicVar;
void publicMethod() {
cout << "Public Method" << endl;
}
};
int main() {
MyClass obj;
obj.publicVar = 5; // Accessible
obj.publicMethod(); // Accessible
return 0;
}
- In this example,
publicVarandpublicMethodare accessible directly through theobjobject.
2. ‘private’ Access Modifier
Description:
- Members declared as
privatecan only be accessed within the class itself. They cannot be accessed or modified from outside the class.
Use Case:
- Use
privatefor data members or methods that should not be exposed outside the class, to enforce encapsulation and protect the integrity of the data.
Example:
class MyClass {
private:
int privateVar;
void privateMethod() {
cout << "Private Method" << endl;
}
public:
void setPrivateVar(int val) {
privateVar = val;
}
int getPrivateVar() {
return privateVar;
}
};
int main() {
MyClass obj;
// obj.privateVar = 5; // Not accessible
// obj.privateMethod(); // Not accessible
obj.setPrivateVar(10); // Accessible
cout << obj.getPrivateVar(); // Accessible
return 0;
}
- In this example,
privateVarandprivateMethodcannot be accessed directly from outside the class. However, the class providespublicmethodssetPrivateVarandgetPrivateVarto access and modify the private member.
3. ‘protected’ Access Modifier
Description:
- Members declared as
protectedcan be accessed within the class itself and by derived classes (classes that inherit from this class). However, they cannot be accessed from outside the class hierarchy.
Use Case:
- Use
protectedfor data members or methods that should be hidden from outside classes but still accessible to derived classes.
Example:
class BaseClass {
protected:
int protectedVar;
public:
void setProtectedVar(int val) {
protectedVar = val;
}
};
class DerivedClass : public BaseClass {
public:
void showProtectedVar() {
cout << "Protected Variable: " << protectedVar << endl;
}
};
int main() {
DerivedClass obj;
obj.setProtectedVar(20); // Accessible
obj.showProtectedVar(); // Accessible
// obj.protectedVar = 30; // Not accessible directly
return 0;
}
- In this example,
protectedVaris accessible withinDerivedClass(because it’s derived fromBaseClass), but not directly from themainfunction or any outside code.

