Examples of Access Declarations


/************************************************************************
*

In the following example, the member b of the base class base is declared public in its base class declaration. Class derived is derived privately from class base. The access declaration in the public section of class derived restores the access level of the member b back to public.

                                                                        *
************************************************************************/

// This example illustrates using access declarations
// to restore base class access.

#include <iostream.h>
class base
{
      char a;
public:
      char c, b;
      void bprint();
};

class derived: private base
{
      char d;
public:
      char e;
      base::b;            // restore access to b in derived
      void dprint();
      derived(char ch) { base::b = ch; }
};

void print(derived& d)
{
      cout << " Here is d " << d.b << endl;
}

void main()
{
      derived obj('c');
      print(obj);
}

/************************************************************************
*

The external function print(derived&) can use the member b of base because the access of b has been restored to public. The external function print(derived&) can also use the members e and dprint() because they are declared with the keyword public in the derived class. The derived class member dprint() can use the members of its own class, d and e, in addition to the inherited members, b, c, and bprint(), that are declared with the keyword public in the base class. The base class member bprint() can use all the members of its own class, a, b , and c.

You can also use an access declaration in a nested class. For example:

class B
{
public:
      class N          // nested class
      {
      public:
            int i;     // public member
      };
};
class D: private B::N  // derive privately
{
public:
      B::N::i;         // restores access to public
};

You cannot convert a pointer to a derived class object to a pointer to a base class object if the base class is private or protected. For example:

class B { /* ... */ };
class D : private B { /* ... */ };      // private base class

void main ()
{
      D d;
      B* ptr;
      ptr = &d;      // error
}

                                                                        *
************************************************************************/