What are the access specifiers of inherited (-> "using") base class ctors / operators in derived class?

111 views Asked by At

In the following code you can see that I'm inheriting the base class ctors into the derived class under the "private" access specifier. My initial thought would be that these would adapt to the access specifiers that I have given (here "private") and hence not be available to use, but I seem to be mistaken. What are the rules for inheriting base class constructors and operators regarding access specifiers in the derived class?

Demo

#include <cstdio>

class base
{
public:
    base(int i) {
        printf("Public base class ctor called!");
    }
private:
    base(bool b) {
        printf("Private base class ctor called!");
    }
};


class derived final : public base
{
private:
    using base::base;
};

int main()
{
    derived d(2);

    // issues "is private within this context"
    // derived e(true);
}

Outputs:

Public base class ctor called!

(expected derived ctor to be "private" in this context)

1

There are 1 answers

1
Vlad from Moscow On

From The C++ 17 Standard (10.3.3 The using declaration)

19 A synonym created by a using-declaration has the usual accessibility for a member-declaration. A using declarator that names a constructor does not create a synonym; instead, the additional constructors are accessible if they would be accessible when used to construct an object of the corresponding base class, and the accessibility of the using-declaration is ignored.

So as in your example the first constructor (with the parameter of the type int) is accessible in the base class then the corresponding inherited constructor in the derived class is also accessible.

On the other hand, the second constructor (with the parameter of the type bool) is private. So for the second object definition of the derived class

derived e(true);

the compiler will issue an error.

In fact inherited constructors also inherit access controls.