C ++ 11 Base delegate / forward constructor for a derived class with the keyword "using"

struct B { B () {} B(int i) {} }; struct D : B { using B::B; // <--- new C++11 feature }; D d1; // ok D d2(3); // ok 

Now, if I add a new constructor inside the struct D body, for example:

 struct D : B { using B::B; D(const char* pc) {} // <--- added }; 

then D d1; starts to give a compilation error ( ideone is not upgraded yet, I'm using g ++ 4.8.0)? However, D d2(3); still working.

Why is the default constructor reset when adding a new constructor inside struct D ?

+7
source share
2 answers

There is a subtle difference between

 struct D : B { using B::B; D(const char* pc) {} // <--- added }; 

against

 struct D : B { using B::B; }; 

In the second case, the compiler will automatically generate the default constructor D () {} ". But if you create your own constructor for D, then the default" D () {} "is no longer available. Of course, you inherited the default constructor B, but this does not tell the compiler how to build D by default.

+4
source

Per GCC 4.8 changes , the compiler must be 4.8.0 to support inheritance constructors.

It seems that after adding a new constructor to D it no longer has a default constructor. eg. C ++ 11

As mentioned in @DyP ( Β§12.9/3 ) ... The compiler dose implicitly declares a default constructor (constructor without parameters) for the derived class D

For each constructor without a template in the set of inherited candidates, constructors other than a constructor without parameters or copy / move having one parameter, the constructor is implicitly declared with the same constructor characteristics, if only there is a constructor with a declared user with the same signature in the class where it appears declaration of use.

0
source

All Articles