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?
Copy constructor is not inherited.
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.
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.
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.
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) { }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With