5

I've been searching for this and I'm amazed I haven't found anything. Why can't I inherit a base class constructor using using declaration and add an overload in the derived class? I'm using Visual C++ 2013, the base class constructor is ignored when default-constructing b:

error C2512: 'B' : no appropriate default constructor available

I've dealt with this by re-defining the constructors, but I don't like that. This is just a minimal example, it wouldn't bother me if I had only one base class constructor.

struct A
{
    A() : a(10) {}

    int a;
};

struct B : A
{
    using A::A;

    explicit B(int a) { this->a = a; }
};

int main()
{
    B b;
}
LogicStuff
  • 19,397
  • 6
  • 54
  • 74
  • That is correct code. See http://stackoverflow.com/questions/9979194/what-is-constructor-inheritance. – R Sahu Apr 06 '15 at 18:57
  • 1
    @RSahu It would be correct without the other constructor in `B`. – David G Apr 06 '15 at 19:07
  • @0x499602D2, that would be silly -- to not allow `B` to add more constructors just because it inherits constructors from `A`. – R Sahu Apr 06 '15 at 19:09
  • 1
    @RSahu `B(int)` is suppressing the creation of a default constructor. He can either remove it or create one himself. – David G Apr 06 '15 at 19:12
  • 1
    @0x499602D2, shouldn't `B` inherit the default constructor from `A` after `using A::A;`? – R Sahu Apr 06 '15 at 19:13
  • 3
    @RSahu [class.inhctor]/p3: For each non-template constructor in the candidate set of inherited constructors [..], a constructor is implicitly declared with the same constructor characteristics unless there is a user-declared constructor with the same signature in the complete class where the using-declaration appears **or the constructor would be a default, copy, or move constructor for that class**. – David G Apr 06 '15 at 19:16
  • 1
    @0x499602D2, Thanks for digging that up. That explains the compiler problem. That would be a perfect answer to the question. – R Sahu Apr 06 '15 at 19:21

1 Answers1

10

The problem is that default-constructors are not inherited. From [class.inhctor]/p3:

For each non-template constructor in the candidate set of inherited constructors [..], a constructor is implicitly declared with the same constructor characteristics unless there is a user-declared constructor with the same signature in the complete class where the using-declaration appears or the constructor would be a default, copy, or move constructor for that class.

You also have a user-declared constructor that suppresses the creation of an implicit default-constructor. Just add a defaulted one to make it work:

B() = default;
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
David G
  • 94,763
  • 41
  • 167
  • 253