The protected access specifier is similar to private, but it also allows access to derived classes. Protected members are not accessible from outside the class, but they can be accessed by derived classes.
Example:
class BaseClass {
protected:
int protectedVar;
void protectedMethod() {
// Code for the protected method
}
};
class DerivedClass : public BaseClass {
public:
void accessProtected() {
protectedVar = 20; // Accessing protected member variable
protectedMethod(); // Calling protected member function
}
};
int main() {
DerivedClass obj;
obj.accessProtected(); // Accessing protected members in derived class
return 0;
}