struct B {
int b;
B(int i = 0) : b(i) {}; // constructor
};
struct D : B {
int d;
};
int main () {
D obj = {1}; // <-- error
// D obj {1}; // <-- error (different)
}
Above code doesn't compiles, and gives:
error: could not convert ‘{1}’ from ‘<brace-enclosed initializer list>’ to ‘D’
The same is true, even if I remove the "constructor" line.
If I remove =
sign, i.e. D obj {1};
then it gives below:
error: no matching function for call to ‘D::D(<brace-enclosed initializer list>)’
What is the correct syntax to fix such issue?
D
doesn't have a constructor taking an int
. If you want it to inherit B
's constructor, say so, like this:
struct D : B {
using B::B;
int d;
};
You probably want to do more than that though, given that D
has another int
member.
A more complete D
which initialises both B::b
(by calling B::B
) and D::d
would probably look like this:
struct D : B {
D(int d_) : B(d_), d(d_) {}
int d;
};
Either way, your code needs to say D
has a constructor taking an int
.
Link to working example using your code and my snippet: http://goo.gl/YbSSHn