Protected Members

Besides the public and private keywords, C++ provides a third keyword controlling the visibility of a class's members: the protected keyword. Protected members are just like private members except that they are accessible to the member functions of derived classes.

As noted earlier, derived classes have no special privileges when it comes to accessing a class's private members. If you want to permit access by only the derived classes, and not by anyone else, you can declare some of your data members as protected. For example:

class Base

{

public:

protected:

int secret;

private:

int topSecret;

};

class Derived : public Base

{

public:

void func();

};

void Derived::func()

{

secret = 1; // Can access protected member

topSecret = 1; // Error: can't access private member

}

void main()

{

Base aBase;

Derived aDerived;

aBase.secret = 1; // Error:

// can't access protected member

aBase.topSecret = 1; // Error: can't access private member

aDerived.secret = 1; // Error:

// can't access protected member

// in derived class either

}

In this example, the private member topSecret is inaccessible to the derived class's member functions, but the protected member secret is accessible. However, the protected member is never accessible to outside functions.

Protected members in the base class are protected members in the derived class too. Functions using the derived class cannot access its protected members.

You should use the protected keyword with care. If the protected portion of a base class is rewritten, all the derived classes that used those protected members must be rewritten as well.