Controlling Access Type
A
using-declaration also enables you to change the access type of a base class's member in a derived class. Consider a
ReadOnly class that enables users to read a file but not to change it. You may need to change the access type of
Write() to private. This can be accomplished by adding a using-declaration to the private section of the class:
class ReadOnly: public File
{
private: //change the access of File::Write
using File::Write;
};
Consequently,
ReadOnly objects cannot invoke this member function:
ReadOnly ro;
ro.Write(mybuff);//error: Write() is not accessible
The Buck Stops Here
Each derived class can override a previous access type. For example, if you have a member function
f() declared public in class A, and a derived class D which changes the access type of
f() to private:
class A
{
public:
int f();
protected:
int g();
};
class D: public A
{
private
using A::f(); //OK, f() is now private
};
A class derived from D may override the access type of
f() once again:
class E : public D
{
public
using A::f(); //OK, f() is public again
};
However, you cannot grant a more permissive access type than the one originally specified in the member's declaration. For example, the member function
g() is declared protected in A. Class F that is derived from A can change
g()'s access to private. A class derived from F may subsequently change
g()'s access back to protected. However, none of them can change
g()'s access type to public. This restriction ensures that the using-declaration facility doesn't violate the fundamental aspects of the C++ object model.