Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 767
xmllmx Avatar asked Oct 22 '25 10:10

xmllmx


1 Answers

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.

like image 198
Anoop Rana Avatar answered Oct 24 '25 00:10

Anoop Rana



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!