C++ : What is the Right way to delete a derived class instance?

c++, destructor, inheritance

Solution

The destructor of A should be virtual. Your problem lies that if you do the following:

A* b = new B( iArr, fArr, dArr );
delete b;

Then B's destructor won't get called because b while being instantiated as a B looks like an A and B's destructor doesn't have an entry in the virtual table which means it doesn't know its there (ie it thinks its just an A)

Edit:

In answer to 1 you could leave the destructor empty or you could not define it.

In answer to 2, you can't really do that. You'd be best off having a virtual protected function called "Destroy" or something thats called from the base class destructor. That is the only way I can think of to control destruction like you describe.

Problem

Assuming we have : ``` class A { protected: int* iArr; float *fArr; public: A(int* iArr,float *fArr); ~A(); } class B : public A { private: double *dArr; public: B(int* iArr,float *fArr,double *dArr); ~B(); } ``` my intuation was that it would only invoke B's destructor but when i ran it on Visual C++ i saw that when destructing an instance of B it calls both A and then B destructor. What is the correct way to write destructor in a derived class then? do i always need to assume parent class would take care of deleting everything but what only the derived class have? Edit: if it is so, then what if the child extending parent class only with overriding functions,does that mean that i leave the child's destructor empty? what if i want to change that? i mean what if i want only child destructor to be called? is there a way to do that?

Original source

Related problems