Turning public into protected
If a class
Person is declared and a
class
Teacher, derived from
Person, is declared:
class Teacher: protected Person{};
The
protected keyword ensures that:
all public members of
Person will be protected in
Teacher,
all protected members of
Person will be protected in
Teacher,
all private members of
Person will be private in
Teacher.
Basically it upgrades the privacy level of the inherited class members to "at least protected".
If the derived class were defined as:
class Teacher : private Person{};
all public and protected base class members would become private in the derived class.
In the following program, the functions
setNameAge() and
printNameAge() are declared as public in the
Person base class. But they are inherited as
protected in the derived
Teacher class,
hence they are unknown outside
Teacher.
For such a reason, the statements commented out in
main():
teacher1.setNameAge("Frank", 78);
teacher1.printNameAge();
couldn't compile if included in the code.
Example
#include <iostream>
#include <string>
using namespace std;
class Person
{
string name;
int age;
public:
void setNameAge(string aName, int anAge)
{
name = aName;
age = anAge;
}
void printNameAge()
{
cout << "name: " << name << " age: " << age << "\n";
}
};
class Teacher : protected Person // all members of Person
// are inherited as protected
{
string subject;
public:
void setSubject(string aSubject)
{
subject = aSubject;
}
void printSubject() {
cout << "subject is: " << subject;
}
};
int main()
{
Person person1;
person1.setNameAge("John" , 23);
Teacher teacher1;
/*
The following two statements would cause a compilation error
if included in the code. The reason is that all public members
of Person have become protected in Teacher, hence they are not
accessible outside the Teacher class.
*/
//teacher1.setNameAge("Frank", 78);
//teacher1.printNameAge();
teacher1.setSubject("Math");
person1.printNameAge();
teacher1.printSubject();
}
Output
name: John age: 23
subject is: Math