Protected Members
If a member of a class
A is declared
as protected, this means that such a member will be unaccessible from
outside the class, just like a private member. But in case a class
B derives from
A, all protected members of A will be
accessible in
B.
The following short program would not compile, because
a cannot be accessed from outside the class:
class A
{
protected:
int a;
};
class B: public A
{
};
int main()
{
B obj;
obj.a = 3; // this causes a compilation error.
// You cannot access from outside the class a protected member
}
In the program below, a class
Person
is declared, then a class
Teacher,
derived from
Person, is declared. All
members of
Person become members of
Teacher. A
Teacher object will contain
name,
age,
setNameAge(),
printNameAge(). Further, it will contain
subject,
setSubject(),
printSubject().
The variables
name and
age are declared as protected in the
Person base class. For such a reason
the function
printSubject(), defined in
the derived class, can access
name and
print it. But the variable
name cannot
be accessed outside the
Person or
Teacher classes.
The line:
cout << teacher1.name;
would cause a compilation error, because
name,
being a protected member, is only accessible within
the
Person and
Teacher classes.
Example
#include <iostream>
##include <string>
using namespace std;
class Person
{
protected:
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 : public Person
{
string subject;
public:
void setSubject(string aSubject)
{
subject = aSubject;
}
void printSubject() // name is a protected variable as
// it is known to the derived class
{
cout << name << "\'s " << "subject is: " << subject;
}
};
int main()
{
Person person1;
person1.setNameAge("John" , 23);
Teacher teacher1;
teacher1.setNameAge("Frank", 78);
teacher1.setSubject("Math");
person1.printNameAge();
teacher1.printNameAge();
teacher1.printSubject();
// the following statement cannot be included in the code.
// cout << teacher1.name;
}
Output
name: John age: 23
name: Frank age: 78
Frank's subject is: Math