Changing the Access of a Class Member

C++Suppose class B is a direct base class of class A. To restrict access of class B to the members of class A, derive B from A using either the access specifiers protected or private.

To increase the access of a member x of class A inherited from class B, use a using declaration. You cannot restrict the access to x with a using declaration. You may increase the access of the following members:

The following example demonstrates this:

struct A {
protected:
  int y;
public:
  int z;
};
 
struct B : private A { };
 
struct C : private A {
public:
  using A::y;
  using A::z;
};
 
struct D : private A {
protected:
  using A::y;
  using A::z;
};
 
struct E : D {
  void f() {
    y = 1;
    z = 2;
  }
};
 
struct F : A {
public:
  using A::y;
private:
  using A::z;
};
 
int main() {
  B obj_B;
//  obj_B.y = 3;
//  obj_B.z = 4;
 
  C obj_C;
  obj_C.y = 5;
  obj_C.z = 6;
 
  D obj_D;
//  obj_D.y = 7;
//  obj_D.z = 8;
 
  F obj_F;
  obj_F.y = 9;
  obj_F.z = 10;
}

The compiler would not allow the following assignments from the above example:

The compiler allows the following statements from the above example:

Related References

IBM Copyright 2003