C++ protected Keyword
Example
Use the protected
keyword to make an attribute accessible to a derived class:
// Base class
class Employee {
protected: // Protected access specifier
int salary;
};
// Derived class
class Programmer: public Employee {
public:
int bonus;
void setSalary(int s) {
salary = s;
}
int getSalary() {
return salary;
}
};
int main() {
Programmer myObj;
myObj.setSalary(50000);
myObj.bonus = 15000;
cout << "Salary: " << myObj.getSalary() << "\n";
cout << "Bonus: " << myObj.bonus << "\n";
return 0;
}
Definition and Usage
The protected
keyword is an access specifier that declares attributes and methods as protected, which means that they are only accessible to methods within the class or methods from one of its derived classes.
Related Pages
Read more about access specifiers in our C++ Access Specifiers Tutorial.
Read more about derived classes in our C++ Inheritance Tutorial.