In a situation where we have a derived class object binded to the base class pointer bPtr
, and a derived class pointer dPtr
pointing to the same object via dynamic_cast<D*>
, what is the proper way to cleanup the resources?
class B {
public:
B() { cout << "B_ctor" << endl; }
virtual ~B() { cout << "B_destructor" << endl; }
virtual void foo() { cout << "B_foo()" << endl; }
};
class D : public B {
public:
D() { cout << "D_ctor" << endl; }
~D() { cout << "D_destructor" << endl; }
void foo() { cout << "D_foo()" << endl; }
};
int main()
{
B * bPtr = new D;
D * dPtr = dynamic_cast<D*>(bPtr);
bPtr->foo();
dPtr->foo();
//delete bPtr;
delete dPtr;
}
I chose to delete dPtr
. I can also choose bPtr
. Whenever I do both VS2015 compiler flashes an error. So my question is what is the standard way to deal with given situation?
Also, whenever I change my code to
D d;
B * bPtr = &d;
D * dPtr = dynamic_cast<D*>(bPtr);
I can't delete neither of pointers. The program just aborts. Why?