C++ class member visibility:
In C++, members of the "protected:" section(s) of a class (or struct) definition are visible only in the class and any derived classes. The protected members of a class are often the elements of its implementation.
The following code snippet shows some of the behaviour (it is based on the code in private, to which you should also compare it). Lines with comments starting "*" are compilation errors; since we're discussing visibility, we must show them.
class X {
protected:
int a;
int square() {
return a*a; // OK (1)
}
public:
X(int val) : a(val) {}
};
class Y : public X {
public:
void print() {
std::cout << a; // OK (2)
}
void square() {
a = square();
}
};
void f()
{
Y y(17);
y.print();
y.square();
y.print();
++ y.a; // * NOT OK (3)
}
Notes:
- Member functions of X have full access to protected: members.
- Y is derived from X, so its member functions also have full access to protected: members of X.
- Encouraged by our success, we might try to access Y::a from code outside of X or a derived class of X. This fails, of course.
You may also declare an inheritance relation between two classes "public". It is very similar to public: visibility of members: only member functions of the class and of further derived classes may use that inheritance. But of course, even they are bound by the visibility of the parent class' methods (just like Y was, in the previous example).
This (like private inheritance) is hardly "inheritance" in the sense of an "is-a" relationship, at least not if outside the class and its derived classes. But that's the whole point: anything outside the implementation cannot tell (from external behaviour) that the inheritance exists. Protected inheritance is sometimes used to model an "implemented-by" relationship; as such, it can be useful for some mixins.