In C++, this optional keyword starts declaring the protected data members and/or member functions. The protected members of a class are moderately accessible by other program parts.

It is invoked thus:

class foo
{
public:
//

protected:
protected data members
protected member functions

private:
//
}

The protected section contains data members and member functions that are not accessible to the class instances and functions that do not belong to the class (such as the main() function). Typically, the protected section contains data members and auxiliary member functions (that is, member functions that work behind the secenes to help other member functions, especially the ones declared in the public section).

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:

  1. Member functions of X have full access to protected: members.
  2. Y is derived from X, so its member functions also have full access to protected: members of X.
  3. 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.

C++ inheritance visibility:

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.

Log in or register to write something here or to contact authors.