Examples of Inherited Member Access Rules


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

The following example demonstrates inherited member access rules.

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

// This example illustrates inherited member access rules.

class B
{
      int a;
public:
      int b,c;
      void f(int) {}
protected:
      int d;
      void g(int) {}
};

class D1 : public B
{
      int a;
public:
      int b;
      void h(int i )
      {
            g(i);              // valid, protected B::g(int)
            B::b = 10;         // valid, B::b (not local b)
            d = 5 ;            // valid, protected B::d
      }
};

class D2 : private B
{
      int e;
public:
      B::c;                         // modify access to B::c
      void h(int i) { d = 5; }      // valid,protected B::d
};

void main( )
{

      int i= 1;      // declare and initialize local variable
      D1 d1;         // create object of class d1
      D2 d2;         // create object of class d2

      d1.a = 5;      // error, D1::a is private in class D1
      d2.b = 10;     // error, B::b is inherited private to
                     // derived class D2
      d2.c = 5;      // valid, modified access from private to public
      d2.B::c = 5;   // valid, public B::c
      d1.c = 5;      // valid, B::c is inherited publicly
      d1.d = 5;      // error, B::d is protected in base class
      d2.e = 10;     // error, private D2::e
      d1.g(i);       // error, g(int) is protected in base class
      d1.h(i);       // valid
      d2.h(i);       // valid
}

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

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