inheriting constructors (ISO 2011 sec 12.9 para 7)

54 Views Asked by At

I am trying out example from ISO 2011 sec 12.9 para 7.Follwing is the code i am tring to compile

int chk;
struct B1 {   B1(int){chk=9;} };
struct B2 {   B2(int){chk=10;} };
struct D2 : B1, B2 {
       using B1::B1;
       using B2::B2;
      D2(int){chk=0;};  
};
int main(){
  B1 b(9);
  D2 d(0);
  return 0;
}

$g++ -std=c++11 sample.cpp Error message

 <source>: In constructor 'D2::D2(int)': <source>:7:10: error: no matching function for call to 'B1::B1()'    D2(int){chk=0;};
      ^ <source>:2:15: note: candidate: B1::B1(int)  struct B1 {   B1(int){chk=9;} };
           ^~ <source>:2:15: note:   candidate expects 1 argument, 0 provided <source>:2:8: note: candidate: constexpr B1::B1(const B1&)  struct B1 {   B1(int){chk=9;} };
    ^~ <source>:2:8: note:   candidate expects 1 argument, 0 provided <source>:2:8: note: candidate: constexpr B1::B1(B1&&) <source>:2:8: note:   candidate expects 1 argument, 0 provided <source>:7:10: error: no matching function for call to 'B2::B2()'    D2(int){chk=0;};
      ^ <source>:3:15: note: candidate: B2::B2(int)  struct B2 {   B2(int){chk=10;} };
           ^~ <source>:3:15: note:   candidate expects 1 argument, 0 provided <source>:3:8: note: candidate: constexpr B2::B2(const B2&)  struct B2 {   B2(int){chk=10;} };
    ^~ <source>:3:8: note:   candidate expects 1 argument, 0 provided <source>:3:8: note: candidate: constexpr B2::B2(B2&&) <source>:3:8: note:   candidate expects 1 argument, 0 provided Compiler exited with result code 1

Is this a bug in gcc?Why is it looking for B1()?I am using gcc 6.3.0

Editing: QUestion in linked question is about when one base class is used.i.e following code

int chk;
struct B1 {   B1(int){chk=9;} };
//struct B2 {   B2(int){chk=10;} };
struct D2 : B1  {
   using B1::B1;
  //using B2::B2;
  //D2(int){chk=0;};  
 };
int main(){
   B1 b(9);
   D2 d(0);
   return 0;
}

Which is working but when D2(int){chk=0;} is introduced thats when the error occurs.

1

There are 1 best solutions below

1
Stephan Lechner On

In D, you provide the sole constructor D2(int){chk=0;}, which does not explicitly call any of the constructors of base classes B1 and B2. Hence, the compiler looks for a default constructor in B1 and B2, which would be implicitly called. But your base structures B1 and B2 do not provide a default constructor...

Hence, either define default constructors in B1 and B2, or call the other constructors explicitly in an initialiser list of D's constructor:

D2(int x):B1(x),B2(x) {chk=0;};