using declarations for modifying access specifiers in derived class

One of the main design principles of C++ as an Object Oriented language is to let each class enforce who can access it’s innards and who can’t. A base class controls it’s access levels even if it is with respect to a base class object embedded within a object of a class derived from Base.

However I read about using declarations that can be allowed to change the access level of a Base class member in a Derived class.

class A{
    protected:
    int n;
};

class B:protected A{
    public:
    using  A::n;
};

int main(){
    B obj;
    obj.n=0;
}

In the example above, I am changing the access level of a protected member to public in the derived class. Is this allowed on purpose? Why couldn’t it be enforced that the access level should be more stringent or equal to how it is in the base class (this can be controlled by the access qualification in the derivation list as well) but cannot be more relaxed than the access level in the base class? Is this allowed because this allows some interesting design patterns? I am just trying to understood why something like this which breaks the principle of encapsulation enforced by a class is allowed?


Source: c++

Leave a Reply