Lecture 2 - Access Modifiers
Lecture 2 - Access Modifiers
In C++, access modifiers are used to specify the visibility and accessibility of class members (variables and
methods). There are three main access modifiers in C++:
1. public
Members declared as public can be accessed from anywhere, both inside and outside the class. It is the
least restrictive access level.
Example:
class MyClass {
public:
int myVar;
void myMethod() {
// Can be called from outside the class
}
};
2. private
Members declared as private can only be accessed by the methods of the same class or by friends of the class. They cannot be
accessed directly from outside the class.
This is the most restrictive access level.
Example:
class MyClass {
private:
int myVar; // Can't be accessed directly from outside
public:
void setVar(int val) {
myVar = val; // Can access private member inside the class
}
int getVar() {
return myVar; // Can access private member inside the class
}
};
3. protected
Members declared as protected can be accessed by the methods of the same class, or by derived classes (subclasses), but not from outside the class
hierarchy.
This access level is useful when you want derived classes to be able to access some of the base class members, but you don't want them to be exposed
publicly.
Example:
class MyClass {
protected:
int myVar; // Accessible to derived classes but not from outside
public:
MyClass() : myVar(0) {}
};
protected:
int protectedVar;
public:
int publicVar;
int getPrivateVar() {
return privateVar; // Accessing private member within the class
}
};
int main() {
MyClass obj;
obj.publicVar = 5; // Can access public members
// obj.privateVar = 10; // Error: private member can't be accessed outside
// obj.protectedVar = 20; // Error: protected member can't be accessed outside
}
Summary:
public: Accessible from anywhere.
private: Accessible only within the class and by friends.
protected: Accessible within the class and by derived classes.