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
public
are 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
public
for 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,
publicVar
andpublicMethod
are accessible directly through theobj
object.
2. ‘private’ Access Modifier
Description:
- Members declared as
private
can only be accessed within the class itself. They cannot be accessed or modified from outside the class.
Use Case:
- Use
private
for 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,
privateVar
andprivateMethod
cannot be accessed directly from outside the class. However, the class providespublic
methodssetPrivateVar
andgetPrivateVar
to access and modify the private member.
3. ‘protected’ Access Modifier
Description:
- Members declared as
protected
can 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
protected
for 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,
protectedVar
is accessible withinDerivedClass
(because it’s derived fromBaseClass
), but not directly from themain
function or any outside code.