I am creating my custom shared pointer class and I want my shared pointer class should call derived class destructor when it goes out of scope for the below code.
...
...
template<class T>
MySharedPtr<T>::MySharedPtr(T * p) : ptr(p), refCnt(new RefCount())
{
refCnt->AddRef();
}
template<class T>
void MySharedPtr<T>::release()
{
if (refCnt->Release() == 0)
{
delete ptr;
delete refCnt;
}
ptr = nullptr;
refCnt = nullptr;
}
...
...
Base class destructor called when it goes out of scope but if I use std::shared_ptr<Base> bptr(new Derived());
, it calls derived destructor and base destructor when it goes out of scope. How can I achieve the same behaviour with my custom class?
class Base
{
public:
Base() {
cout << "Base default constructor" << endl;
}
~Base() {
cout << "Base destructor" << endl;
}
virtual void display() {
cout << "in Base" << endl;
}
};
class Derived : public Base
{
public:
Derived() {
cout << "Derived default constructor" << endl;
}
~Derived() {
cout << "Derived destructor" << endl;
}
virtual void display() {
cout << "in Derived" << endl;
}
};
int main()
{
MySharedPtr<Base> bptr(new Derived());
bptr->display();
}