Changing the access of a class member (C++ only)
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:
- A member inherited as
private. (You cannot increase the access of a member declared asprivatebecause a using declaration must have access to the member's name.) - A member either inherited or declared as
protected
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:
obj_B.y = 3andobj_B.z = 4: Membersyandzhave been inherited asprivate.obj_D.y = 7andobj_D.z = 8: Membersyandzhave been inherited asprivate, but their access have been changed toprotected.
y = 1andz = 2inD::f(): Membersyandzhave been inherited asprivate, but their access have been changed toprotected.obj_C.y = 5andobj_C.z = 6: Membersyandzhave been inherited asprivate, but their access have been changed topublic.obj_F.y = 9: The access of memberyhas been changed fromprotectedtopublic.obj_F.z = 10: The access of memberzis stillpublic. Theprivateusing declarationusing A::zhas no effect on the access ofz.
Related information