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

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

void print(B b) {}

int main(int argc, char** argv) {
    print(1);
    return 0;
}

This code does not compile... Even with 'using A::A' in struct B public section, B still does not have a public constructor accepting an int (but it has a protected one).

It seems that :

I can inherit public constructor with 'using'

I can re-declare as public in derived class any method defined in base class (private or protected or else)

BUT I cannot do the same with a constructor : no way to alter its visibility with 'using'

Why ?

2 Answers2

4

This is intentional. Note that A::A inherits every constructor, not just the one you are expecting. Applying the using's access modifier to every inherited constructor would likely be too far reaching. Instead, it simply makes them available for overload resolution.

From cppreference :

If the using-declaration refers to a constructor of a direct base of the class being defined (e.g. using Base::Base;), all constructors of that base (ignoring member access) are made visible to overload resolution when initializing the derived class.

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.

If you want to call A::A(int) when constructing a B, you can implement B::B(int) yourself such that it calls it.

Community
  • 1
  • 1
François Andrieux
  • 28,148
  • 6
  • 56
  • 87
0

If the current access specifier of the using declaration changed the access specifier of the "inherited" constructors, then there would be no way for separate "inherited" constructors to have different access specifier.

If the base class does have multiple constructors with differing access, then it would be typically desirable for the accessibility to remain in the derived class. The rules of using make this possible.

eerorika
  • 232,697
  • 12
  • 197
  • 326