Regarding Virtual Destructor | Sololearn: Learn to code for FREE!


Regarding Virtual Destructor

I have two classes Parent and child. Child is derived from Parent class. Parent class is having Show method as virtual. But it do not contain any virtual destructor. Parent *p; Child c; p = &c; p->show(); delete p; When i run the above code it calls both classes destructor. But as i read somewhere in case of upcasting if base class destructor is not virtual then compiler will not call derived class destructor. And 2nd Scenario with Same above classes, when i write below piece of code inside main, Parent *p = new Derived; p->show(); delete p; Then its just called base class destructor and not derived. Can someone tell me the difference? Why in first scenario it has called base plus derived both?


11/17/2019 7:04:57 AM

Amit chavare

4 Answers

New Answer


In first case how can u apply delete operator to pointer p which points to statically allowed object c.... That's not correct... And the deatructor is getting called for c because it's a object whose scope will end when main() ends


In second case it's the actual deletion taking place through delete operator which is applied to base pointer... Hence no derived class destructor call...


In simple terms u should delete only stuff u allocate through new or get unexpected results


Thanks Saurabh B