Search code examples
c++c++11inheritancestandardsusing-declaration

Why can't C++ using-declaration expose a protected member of base as a public member of derived?


As per cppref:

Using-declaration introduces a member of a base class into the derived class definition, such as to expose a protected member of base as public member of derived.

However, the following code can't compile:

class A {
protected:
    A(int, int) {
    }
};

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

int main() {
    B(1, 2); // error: calling a protected constructor of class 'A'
}

Why can't C++ using-declaration expose a protected member of base as a public member of derived as expected?


Solution

  • Note on the same page the section on inheriting constructors states:

    If overload resolution selects an inherited constructor, it is accessible if it would be accessible when used to construct an object of the corresponding base class: the accessibility of the using-declaration that introduced it is ignored.

    (emphasis mine)

    Note the emphasized part "the accessibility of the using-declaration that introduced it is ignored". And since the base class constructor A::A(int, int) is protected(meaning it is inaccessible inside main), we get the mentioned error.


    The same can be seen from namespace.udecl#16:

    A using-declaration has the usual accessibility for a member-declaration. Base-class constructors considered because of a using-declarator are accessible if they would be accessible when used to construct an object of the base class; the accessibility of the using-declaration is ignored.