Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class inherited from class without default constructor

Right now I have a class A that inherits from class B, and B does not have a default constructor. I am trying the create a constructor for A that has the exact same parameters for B's constructor

struct B {
  int n;
  B(int i) : n(i) {}
};

struct A : B {
  A(int i) {
    // ...
  }
}; 

but I get:

error: no matching function for call to ‘B::B()’
note: candidates are: B::B(int)

How would I fix this error?

like image 280
wrongusername Avatar asked Sep 15 '10 01:09

wrongusername


1 Answers

The constructor should look like this:

A(int i) : B(i) {}

The bit after the colon means, "initialize the B base class sub object of this object using its int constructor, with the value i".

I guess that you didn't provide an initializer for B, and hence by default the compiler attempts to initialize it with the non-existent no-args constructor.

like image 119
Steve Jessop Avatar answered Sep 24 '22 21:09

Steve Jessop