Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of 'using' keyword to make inherited constructor public [duplicate]

I am trying to test protected methods and constructors of my class. For this purpose, I tried to subclass it, and re-export its members as public with C++11 using keyword:

class Foo {
  protected:
   Foo(int i) {}
   void run() {}
};

class TestableFoo : public Foo {
  public:
   using Foo::Foo;
   using Foo::run;
};

int main() {
  TestableFoo foo(7);
  foo.run();
}

However, both g++ and clang++ fail to compile it, producing the following error:

test.cpp:13:15: error: ‘TestableFoo::TestableFoo(int)’ is protected
    using Foo::Foo;
               ^
test.cpp:18:16: error: within this context
   TestableFoo foo(7);
                    ^

TestableFoo constructor is still protected, even though run method becomes public (I confirmed it separately). Why is that so? I could understand either decision (inheriting vs. overwriting visibility), but why is there an inconsistency between methods and constructors?

like image 937
rburny Avatar asked Jul 08 '14 15:07

rburny


People also ask

Can we inherit copy constructor?

Copy constructor is not inherited.

What is the use of using declaration?

A using declaration introduces an unqualified name as a synonym for an entity declared elsewhere. It allows a single name from a specific namespace to be used without explicit qualification in the declaration region in which it appears.

What is the role of inheritance to constructor?

Constructor in Multiple Inheritance in C++ The main job of the constructor is to allocate memory for class objects. Constructor is automatically called when the object is created. Multiple Inheritance: Multiple Inheritance is a feature of C++ where a class can derive from several(two or more) base classes.

How do you inherit constructors?

To inherit only selected ones you need to write the individual constructors manually and call the base constructor as needed from them. Historically constructors could not be inherited in the C++03 standard. You needed to inherit them manually one by one by calling base implementation on your own.


1 Answers

The Standard explicitly states that inherited constructors retain their access levels:

12.9 Inheriting constructors [class.inhctor]

1 A using-declaration (7.3.3) that names a constructor implicitly declares a set of inheriting constructors. The candidate set of inherited constructors from the class X named in the using-declaration consists of actual constructors and notional constructors that result from the transformation of defaulted parameters as follows:

[list of cases omitted]

4 A constructor so declared has the same access as the corresponding constructor in X. It is deleted if the corresponding constructor in X is deleted (8.4).

You can call it directly of course:

TestableFoo(int i) : Foo(i) { }
like image 116
TemplateRex Avatar answered Nov 03 '22 08:11

TemplateRex