// We all know that a protected variable of a class is accessible in the class
// derived from it. This example shows that the protected variable of a class
// is accessible to any depth in the class hierarchy.
#include
class X {
protected:
char c;
public:
X (char val);
void fooX();
};
class Y : public X {
public:
Y (char val);
void fooY();
};
class Z : public Y {
public:
Z (char val);
void fooZ();
};
X::X(char val) { c = val; }
Y::Y(char val): X(val) { }
Z::Z(char val): Y(val) { }
// c is data member of X, so it can be accessed inside a member function of X.
void X::fooX() { cout << c << endl; }
// c is a protected data member of X, and Y is derived from X. So, it is legal
// to access c in Y.
void Y::fooY() { cout << c << endl; }
// c is protected data member of X. Z is derived from Y and Y is derived from
// X. So, c can be accessed inside Z also.
void Z::fooZ() { cout << c << endl; }
int main () {
X obj_x('x');
Y obj_y('y');
Z obj_z('z');
obj_x.fooX();
obj_y.fooY();
obj_z.fooZ();
return 0;
}
See the output of this program