When I try to run this code:
class A : public enable_shared_from_this<A> {
public:
A() {
cout << "A::A()" << endl;
};
virtual ~A() {
cout << "A::~A()" << endl;
};
virtual void func() {
cout << "A::func" << endl;
auto ptr = shared_from_this();
ptr->dosomething();
}
virtual void dosomething() {
cout << "A::dosomething" << endl;
}
};
class B : public A {
public:
B() {
cout << "B::B()" << endl;
};
~B() {
cout << "B::~B()" << endl;
};
void func() override {
cout << "B::func" << endl;
A::func();
}
void dosomething() override {
cout << "B::dosomething" << endl;
}
};
int main() {
shared_ptr<B> pb = make_shared<B>();
//shared_ptr<A> pa = make_shared<A>();
pb->func();
}
The result I get is:
A::A()
B::B()
B::func
A::func
B::dosomething
B::~B()
A::~A()
The call chain is B::func->A::func->ptr->dosomething, this indicates that the return value of shared_from_this() is a shared_ptr<B>. Why is the result of calling shared_from_this() not shared_ptr<A>?