I'm having a problem initializing a shared_ptr member of a class I'm working on.
I have two classes, A and B:
class A {
int _x;
int _y;
public:
A(int, int);
};
A::A(int x, int y) {
_x = x;
_y = y;
}
class B : public A {
std::shared_ptr<A> _a;
public:
B(std::shared_ptr<A>);
};
B::B(std::shared_ptr<A> a) : _a(a) {}
int main() {
std::shared_ptr<A> a = std::make_shared<A>(1, 2);
B b(a);
return 0;
}
I just want class B to hold a std::shared_ptr to an instance of class A.
However, I'm getting the error no matching function for call to A::A() in B's constructor.
I'm confused because I thought the point of the initializer list is to avoid implicitly calling the default constructor for member variables, but it still seems to be trying to call A's default constructor.
Any explanation is appreciated, thanks.
edit: after more messing around, it seems like it complies properly if B does not inherit from A. Still unsure why inheriting from A results in A's default constructor being called from B's constructor.
Ais implicitly called in the constructor ofB:B::B(std::shared_ptr<A> a) : _a(a) {}. BecauseBinherits fromAa constructor ofAhas to be called whenBis constructed.Bto inherit fromAand have ashared_ptrtoAat the same time?class B : Ameans that eachBcontains anA. You need to initialize that object somehow. If you don't initialize it in the member initializer list (you aren't) then it defaults to using the default constructor, which doesn't exist. ThereforeBmust be rejected.Bto hold ashared_ptrtoA, why isBderived fromAwhich makes it do more than just hold ashared_ptr?it seems like it complies properly if B does not inherit from A